require 'fileutils'

module Kz
  EXIT_PROCS = []
  class << self
    def barrier(default=nil)
      yield
    rescue Exception
      print_error($!)
      default
    end

    def print_warning(message)
      STDERR.puts("** KzRuby WARNING **: #{message}")
    end

    def print_error(err)
      print_warning(err.class)
      STDERR.puts(err.message)
      STDERR.puts(err.backtrace)
    end

    def add_exit_proc(pr=Proc.new)
      EXIT_PROCS << pr
    end

    def invoke_exit_procs
      EXIT_PROCS.each do |pr|
        begin
          pr.call
        rescue Exception
          print_error($!)
        end
      end
    end

    def _exit
      invoke_exit_procs
    end

    def exit
      _exit
    rescue Exception
      print_error($!)
    end
  end

  begin
    require 'gtk2'
    ENABLE = true
    TMP_DIR = File.join(GLib.tmp_dir, PACKAGE)
    barrier do
      FileUtils.rm_rf(TMP_DIR)
      FileUtils.mkdir_p(TMP_DIR)
      add_exit_proc do
        FileUtils.rm_rf(TMP_DIR)
      end
    end
  rescue Exception
    ENABLE = false
    print_warning(_("Ruby extension disabled: failed require 'gtk2'"))
  end
end
