# Dropzone Action Info
# Name: %service-name%
# Description: This action sends the dropped items to BetterZip to extract them with the preset %preset-name%. When clicked, BetterZip is activated.
# Handles: Files
# Creator: Robert Rezabek
# URL: https://macitbetter.com/
# Events: Clicked, Dragged
# KeyModifiers: Command, Option, Control, Shift
# SkipConfig: Yes
# RunsSandboxed: No
# Version: 1.0
# MinDropzoneVersion: 3.5

require 'cgi'

# Read BetterZip's per-install local-origin token so it knows this request comes from
# the user's own machine and skips the confirmation dialog. Absent token still works.
def read_betterzip_token
	path = File.expand_path("~/Library/Application Support/com.macitbetter.betterzip/url-token")
	begin
		File.read(path).strip
	rescue
		""
	end
end

def dragged
	$dz.determinate(true)
	$dz.percent(0)
	
	isPathParam = ""
	if ENV['dragged_type'] == "files"
		isPathParam = "isPath YES"
	end

	# CGI.escape encodes spaces as "+", which BetterZip's percent-decoding leaves as literal "+"
	files = ($items.map {|x| CGI.escape(x).gsub("+", "%20")} ).join (";")

	preset = CGI.escape("%preset-name%").gsub("+", "%20")
	token = read_betterzip_token
	fragment = token.empty? ? "" : "##{token}"
	system("open \"btrzp://extract/#{preset}?#{files}#{fragment}\"")

	$dz.url(false)
end

def clicked
	%x(open -a BetterZip.app >& /dev/null)
	$dz.url(false)
end

