(local { : Gtk : Gdk : WebKit2 : cairo } (require :lgi))
(local { : view } (require :fennel))
(local Command (require :command))

(var frames [])

(fn new-frame []
  (let [hpad 2
        vpad 2
        window (Gtk.Window {
                            :title "Dunlin"
                            :default_width 800
                            :default_height 720
                            :on_destroy Gtk.main_quit
                            })
        container (Gtk.Box {
                            :orientation Gtk.Orientation.VERTICAL
                            })
        progress-bar (Gtk.ProgressBar {
                                       :orientation Gtk.Orientation.HORIZONTAL
                                       :fraction 1.0
                                       :margin 0
                                       })
        contentwidget (Gtk.Box {
                                :orientation Gtk.Orientation.VERTICAL
                                })
        ]
    (tset Command.widget :on_activate
          (fn [event]
            (let [result (Command.on-input event.text)]
              (set  Command.widget.placeholder_text
                   (or result.prompt ""))
              (set Command.widget.sensitive result.active)
              (set Command.widget.text
                   (or result.default result.error "")))))

    (tset window :on_key_release_event
          (fn [window event]
            (when (and (not (Command.active?))
                       (= event.keyval (string.byte "g")))
              (Command.invoke-interactively
               "visit-location"
               {:buffer "main"}))
            (when (and event.state.MOD1_MASK
                       (= event.keyval (string.byte "x")))
              (Command.activate))))

    (doto container
      (: :pack_start  Command.widget false false vpad)
      (: :pack_start progress-bar false false vpad)
      (: :pack_start contentwidget true true vpad))
    (window:add container)
    (window:show_all)
    (let [f
          {
           :window window
           :buffer nil
           :content contentwidget
           :show-buffer (fn [self b]
                          (each [_ w (pairs (contentwidget:get_children))]
                            (w:hide))
                          (contentwidget:pack_start b.webview true true 0)
                          (b.webview:show))
           }]
      (table.insert frames f)
      f)))


{ :new new-frame :frames frames }