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
  name = 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.set_text(_("Installed Ruby extension successfully"), name)
    Kz.pop_statusbar(kz, name, statusbar_timeout)
  end
  dl.signal_connect("error") do
    kz.statusbar.set_text(_("Failed Ruby extension install"), name)
    Kz.pop_statusbar(kz, name, 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
