require 'fileutils'
require 'uri'

def extract_extension_filename_from_uri(uri)
  uri = URI(uri)
  base = nil
  if uri.scheme == "file"
    if /#{File::SEPARATOR}\z/ !~ uri.path
      base = File.basename(uri.path)
    end
  else
    if /\/\z/ !~ uri.path
      base = uri.path.split(/\//).last
    end
  end
  base ||= "index.rb"
  base = File.basename(base, ".*") + ".rb"
  File.join(Kz::ACTIONS_DIR, base)
end

def act_install_as_ruby_extension(action, group, kz)
  statusbar_timeout = 3 * 1000
  statusbar_id = kz.statusbar.get_context_id(action.name)
  uri = nil
  uri = kz.mouse_event_info.link if kz.mouse_event_info
  uri = kz.current_page.location if uri.nil? and kz.current_page
  return if uri.nil?
  filename = extract_extension_filename_from_uri(uri)
  FileUtils.mkdir_p(File.dirname(filename))

  dl = Kz::Downloader.new(uri, filename)
  dl.signal_connect("completed") do
    Kz::Actions.install_action(kz, filename)
    kz.statusbar.push(statusbar_id, _("installed Ruby extension successfully"))
    Kz.pop_statusbar(kz, statusbar_id, statusbar_timeout)
  end
  dl.signal_connect("error") do
    kz.statusbar.push(statusbar_id, _("failed Ruby extension install"))
    Kz.pop_statusbar(kz, statusbar_id, statusbar_timeout)
  end
  Kz::DownloaderGroup.add(dl)
  dl.to_file
end
def act_install_as_ruby_extension_config(config, kz)
  config[:label] = N_("Install as Ruby extension")
  config[:tooltip] = N_("download and register as Ruby extension")
end
