# Dropzone Action Info
# Name: Imgur
# Description: Uploads an image to Imgur.\n\nThe link to the image will be put on the clipboard after the upload completes.
# Handles: Files
# Creator: Aptonic
# URL: https://aptonic.com
# OptionsNIB: Imgur
# Events: Clicked, Dragged
# KeyModifiers: Option
# SkipConfig: No
# RunsSandboxed: Yes
# Version: 1.0
# MinDropzoneVersion: 4.0

require 'imgur'
require 'curl_uploader'

def dragged
  imgur = Imgur.new

  $dz.determinate(false)

  allowed_exts = ["jpg", "jpeg", "gif", "tif", "tiff", "png", "bmp", "heic"]

  # Check only supported types were dragged
  $items.each do |item|
    filename = File.basename(item)
    ext = File.extname(item).downcase[1..-1]
    $dz.fail("Only image files are supported") if not allowed_exts.include?(ext)
  end

  # Convert HEIC files to JPG
  converted_items = []
  temp_files = []
  $items.each do |item|
    ext = File.extname(item).downcase[1..-1]
    if ext == "heic"
      converted_path = convert_heic_to_jpg(item)
      converted_items << converted_path
      temp_files << converted_path
    else
      converted_items << item
    end
  end

  $items = converted_items

  if $items.length > 1
    $dz.error("Imgur Album Upload", "The Imgur API no longer supports albums.\n\nWe recommend switching to the ImgBB action instead for this.")
  end

  uploader = CurlUploader.new
  uploader.upload_url = "https://api.imgur.com/3/image"
  uploader.file_field_name = "image"

  access_token = nil

  if ENV["access_token"]
    # Renew the access token and set Authorization: Bearer header accordingly
    access_token = imgur.renew_auth_token(ENV['client_id'], ENV['client_secret'], ENV['refresh_token'])

    unless access_token
      $dz.error("Failed to renew auth token", "Try removing and readding your Imgur account.\n\nDebug Info:: #{imgur.error_message}")
    end

    uploader.headers["Authorization"] = "Bearer #{access_token}"
  else
    uploader.headers["Authorization"] = "Client-ID #{ENV['client_id']}"
  end

  # Just do the upload and put URL on clipboard
  result = uploader.upload($items)[0]
  puts result.inspect
  check_upload_output_valid(result)

  # Clean up temporary converted files
  temp_files.each do |temp_file|
    File.delete(temp_file) if File.exist?(temp_file)
  end

  if ENV["KEY_MODIFIERS"] == "Option"
    finish("https://imgur.com/" + result[:output]["data"]["id"])
  else
    finish(result[:output]["data"]["link"])
  end
end

def check_upload_output_valid(result)
  json_result = result[:output]
  if result[:curl_output_valid] and json_result["success"] and json_result["data"]
    return true
  else
    error_message = json_result
    if json_result["data"] and json_result["data"]["error"]
      error_message = json_result["data"]["error"]
    end
    $dz.fail(error_message)
  end
end

def finish(url, title=nil)
  $dz.finish("URL is now on clipboard")
  $dz.url(url, title)
end

def clicked
  if ENV["access_token"]
    system("open https://#{ENV['account_username']}.imgur.com/all/")
  else
    system("open https://imgur.com")
  end
end

def convert_heic_to_jpg(heic_path)
  filename = File.basename(heic_path, ".*") + ".jpg"
  output_path = File.join($dz.temp_folder, filename)

  # Use sips to convert HEIC to JPG
  result = `sips -s format jpeg "#{heic_path}" --out "#{output_path}" 2>&1`

  if $?.exitstatus != 0
    $dz.fail("Failed to convert HEIC file: #{result}")
  end

  return output_path
end
