# Dropzone Action Info
# Name: Rename & Copy Files
# Description: Allows you to rename and copy dropped files to a specified folder.
# Handles: Files
# Creator: Aptonic
# URL: https://aptonic.com
# OptionsNIB: ChooseFolderRename
# UseSelectedItemNameAndIcon: Yes
# Events: Clicked, Dragged
# SkipConfig: No
# RunsSandboxed: Yes
# Version: 1.0
# MinDropzoneVersion: 4.0

def dragged
  $dz.determinate(true)

  move = false
  operation = "Copying"
  
  from_mailapp = false

  $items.each do |item|
    if item.include?("com.apple.mail")
      from_mailapp = true
      break
    end
  end
  
  if not ENV['sandboxed'] and not from_mailapp
    # Rename files before copy if possible so that we can check during do_copy if would replace at destination
    # with correct new filenames, this is not possible when sandboxed as no permission
    renamed_files = Array.new 
    for index in 0...$items.size
      renamed_file_path = File.dirname($items[index]) + "/" + ENV["RENAMED_FILENAME_#{index}"]
      File.rename($items[index], renamed_file_path)
      renamed_files.push(renamed_file_path)
    end
  end
  
  $dz.begin("#{operation} files...")
  Rsync.do_copy(((ENV['sandboxed'] or (not ENV['sandboxed'] and from_mailapp)) ? $items : renamed_files), ENV['EXTRA_PATH'], move)
  
  if ENV['sandboxed'] or from_mailapp
    # Rename files after copy to destination which we have permission to
    for index in 0...$items.size
      new_file_path = ENV['EXTRA_PATH'] + "/" + File.basename($items[index])
      File.rename(new_file_path, ENV['EXTRA_PATH'] + "/" + ENV["RENAMED_FILENAME_#{index}"])
    end
  end
  
  if not move and not ENV['sandboxed'] and not from_mailapp
    # Rename source files back when copying
    for index in 0...renamed_files.size
      File.rename(renamed_files[index], $items[index])
    end
  end
  
  finish_op = (move ? "Move" : "Copy")
  last_component = ENV['EXTRA_PATH'].split('/').last.gsub(/^(.{30,}?).*$/m,'\1...')
  
  if ENV['open_after_rename'] == "1"
    for index in 0...$items.size
      new_file_path = ENV['EXTRA_PATH'] + "/" + ENV["RENAMED_FILENAME_#{index}"]
      escaped_path = new_file_path.gsub(/["`$\\]/){ |s| '\\' + s }
      system("open \"#{escaped_path}\"") if File.exist?(new_file_path)
    end
  end

  $dz.finish("Click here to open the '#{last_component}' folder")
  $dz.url(false)
end

def clicked
  escaped_path = ENV['EXTRA_PATH'].gsub(/["`$\\]/){ |s| '\\' + s }
  system("open \"#{escaped_path}\"")
end
