#!/usr/bin/ruby

class Dropzone
  $VERBOSE = nil

  def determinate(value)
    output = (value ? "Determinate: 1" : "Determinate: 0")
    send_output(output)
  end
  
  def begin(message)
    send_output("Begin_Message: #{message}")
  end
  
  def finish(message)
    send_output("Finish_Message: #{message}")
  end

  def fail(message)
    send_output("Fail: #{message}")
    Process.exit
  end

  def alert(title, message)
    send_output("Alert_Title: #{title}")
    send_output("Alert: #{message}")
  end
  
  def error(title, message)
    send_output("Error_Title: #{title}")
    send_output("Error: #{message}")
    Process.exit
  end
  
  def percent(value)
    send_output("Progress: #{value}")
  end
  
  def url(url, title=nil)
    send_output("URL_Title: #{title}") if title
    (url ? send_output("URL: #{url}") : send_output("URL: 0"))
  end
  
  def text(text)
    (text ? send_output("Text: #{text}") : send_output("Text: 0"))
  end

  def temp_folder
    temp_folder = ENV['support_folder'] + '/' + 'Temp'
    Dir.mkdir temp_folder unless File.directory?(temp_folder)
    return temp_folder
  end

  def save_value(value_name, value)
    send_output("Save_Value_Name: #{value_name}")
    send_output("Save_Value: #{value}")
  end

  def remove_value(value_name)
    send_output("Remove_Value_Name: #{value_name}")
  end

  def add_dropbar(file_paths)
    if ENV['sandboxed']
      tfolder = temp_folder
      file_paths.each do |path|
        unless path.start_with?(tfolder)
          error("Not Supported in Mac App Store version", "You cannot use the add_dropbar() API method in the Mac App Store version of Dropzone.\n\nPlease download the non-Mac App Store version of Dropzone.")
        end
      end
    end
    file_paths.each do |path|
      send_output("Add_Dropbar: #{path}")
    end
    send_output("Complete_Add_Dropbar: 1")
    sleep(1)
  end
  
  def select_folder(prompt)
    return send_output("Select_Folder: #{prompt}")
  end

  def pashua(config)
    pashua_run(config)
  end
  
  def notification_applescript(applescript)
    send_output("Notification_AppleScript: #{applescript}")
  end

  def inputbox(title, prompt_text, field_name="Filename")
      
config = <<EOS
*.title = #{title}
txt.type = textfield
txt.label = #{prompt_text}
cb.type = cancelbutton
EOS

    result = pashua(config)

    if result['cb'] == "1"
      fail("Cancelled")
    end

    unless result['txt']
      fail("#{field_name} cannot be empty.")
    end

    return result['txt']
  end

  def read_clipboard
    IO.popen('pbpaste') {|clipboard| clipboard.read}
  end

  def send_output(line)
    puts line.gsub(/\n/, "[;n")
    # Block until acknowledgement
    return $stdin.gets
  end
end
