/* This file is part of GPump, a Pump.io client.
 *
 * GPump (THE SOFTWARE) is made available under the terms and conditions of the
 * GNU Lesser General Public Licence 3.0. A copy of the licence can be read
 * in the file lgpl-3.0.txt in the root of this project.
 */


const Gettext = imports.gettext;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const _ = imports.gettext.gettext;
const Lang = imports.lang;

const SettingsData = imports.settings_data;
/* const Style = imports.style; */
const PreferencesUI = imports.preferences_ui;
const UserMenu = imports.user_menu;
const UserButton = imports.user_button;

/** @class
 * This class is the main application class, it creates the main wiev
 * and basically is what runs the program.
 */
const Application = new Lang.Class ({
  Name: "Application",
  Extends: Gtk.Application,
  
  _init: function () {
    this.settings = SettingsData.get_settings ();
    
    Gettext.bindtextdomain ("gpump", "./locale/"); //FIXME
    Gettext.textdomain ("gpump");
    GLib.set_prgname ("gpump");
    
    this.parent ({
      application_id: "org.gego.gpump",
      flags: Gio.ApplicationFlags.FLAGS_NONE,
      register_session: true,
    });
    GLib.set_application_name (_("GPump"));
    
  },
  
  vfunc_activate: function () {
    /* Guarantee that only one window is present at any time. */
    let w_list = this.get_windows ();
    if (w_list.length) {
      w_list[0].present ();
      w_list[0].move (this.settings.get_setting ("ui.x").data,
                             this.settings.get_setting ("ui.y").data);
      return;
    }
    
    this._prepare_window ();
    this._prepare_app_menu ();
    this._prepare_header_bar ();
    
    /* Style.load_css (); */
    
    this.window.show_all ();
  },
  
  /**
   * This function is used to prepare the window, it also initializes and adds
   * the headerbar to it.
   */
  _prepare_window: function () {
    
    this.window = new Gtk.ApplicationWindow ({
      application: this,
      type: Gtk.WindowType.TOPLEVEL,
      title: GLib.get_application_name (),
      default_height: 500,
      default_width: 500,
      height_request: 500,
      width_request: 500,
      window_position: Gtk.WindowPosition.CENTER
    });
    
    this.window.set_titlebar ((this.headerbar = new Gtk.HeaderBar({
      title: GLib.get_application_name (),
      subtitle: _("A Pump.io client"),
      show_close_button: true
    })));
    
    if (!(this.settings.get_setting ("ui.x").data < 0 &&
        this.settings.get_setting ("ui.y").data < 0)){
      this.window.move (this.settings.get_setting ("ui.x").data,
                                       this.settings.get_setting ("ui.y").data);
    }
    
    var gtk_settings = Gtk.Settings.get_default ();
      if ( this.settings.get_setting ("main.use_dark").data ) {
        gtk_settings["gtk_application_prefer_dark_theme"] = true;
      } else {
        gtk_settings["gtk_application_prefer_dark_theme"] = false;
      }
    
    print ("derp!\n");
    
    
    
    this.window.add ((this.layout = new Gtk.Box ({
      orientation: Gtk.Orientation.VERTICAL
    })));
    
    /* * Building the stack switched views */
    /* switcher */
    /* Hack to centre the damn switcher */
    this.layout.pack_start ((this.switcher_box = new Gtk.Box ({
      orientation: Gtk.Orientation.HORIZONTAL
    })), false, false, 0);
    
    this.switcher_box.set_center_widget (
      (this.stack_switcher = new Gtk.StackSwitcher ())
    );
    
    /* the stack */
    this.layout.pack_end ((this.stack = new Gtk.Stack ({
      homogeneous: true,
      transition_duration: 250,
      transition_type: Gtk.StackTransitionType.CROSSFADE
    })), true, true, 0);
    
    /* main view */
    this.stack.add_titled ((new Gtk.ScrolledWindow ({
      child: (this.main_list_box = new Gtk.ListBox()),
      margin: 1
    })), "main", _("Main"));
    
    
    /* 'mean while' view */
    this.stack.add_titled ((new Gtk.ScrolledWindow ({
      child: (this.mw_list_box = new Gtk.ListBox()),
      margin: 1
    })), "meanwhile", _("Meanwhile"));
    
    /* * Hook up the stack and the stack switcher */
    this.stack_switcher.set_stack (this.stack);
    
    /* * Hide the window so, so we can show it later */
    this.window.connect ('delete_event',
                         Lang.bind (this, function () {
      print ("balls to it!");
      this._save_settings ();
      this.window.hide ();
      /* To Prevent the widow from rely being destroyed? */
      return true;
    }));
    
    this.add_window (this.window);
  },
  
  /**
   * This function is used to create the application menu.
   */
  _prepare_app_menu: function () {
    let menu = new Gio.Menu ();
    let section = new Gio.Menu ();
    
    section.append (_("Preferences"), "app.preferences");
    menu.append_section (null, section);
    
    section = new Gio.Menu ();
    section.append (_("About"), "app.about");
    section.append (_("Quit"), "app.quit");
    menu.append_section (null, section);
    
    this.set_app_menu (menu);
    
    let about_action = new Gio.SimpleAction ({name: "about"});
    about_action.connect ('activate', Lang.bind (this, function () {
      let about_dialog = new Gtk.AboutDialog ({use_header_bar: true,
        transient_for: this.window,
        modal: true,
        version: "pre-alpha ~BZR~",
        program_name: GLib.get_application_name (),
        copyright: "Gustav \'Gego/XAREN\' Hartvigsson, 2014",
        license_type: Gtk.License.LGPL_3_0});
      
      about_dialog.authors =
                          ["Gustav Hartvigsson <gustav.hartvigsson@gmail.com>"];
      about_dialog.connect ("response", function () {
        about_dialog.destroy ();
      });
      about_dialog.run ();
    }));
    this.add_action (about_action);
    
    let quit_action = new Gio.SimpleAction ({name: "quit"});
    quit_action.connect ('activate', Lang.bind (this, function () {
      this._save_settings ();
      this.quit ();
    }));
    this.add_action (quit_action);
    
    let preferences_action = new Gio.SimpleAction ({name: "preferences"});
    preferences_action.connect ('activate', Lang.bind (this, function (){
      let pref_dialog = new PreferencesUI.PreferencesUI ({
        transient_for: this.window
      });
      pref_dialog.run ();
    }));
    this.add_action (preferences_action);
  },
  
  /**
   * This function is used to prepare the hearderbar by adding buttons and
   * assigning callback functions to them.
   */
  _prepare_header_bar: function () {
    
    this.headerbar.pack_start ((this.new_post_btn = new Gtk.Button ({
      image: (new Gtk.Image ({icon_name: 'text-editor-symbolic'})),
      tooltip_text: _("Create new post"),
    })));
    
   this.new_post_btn.get_style_context ().add_class ("image-button");
    
    this.headerbar.pack_start ((this.refresh_btn = new Gtk.Button({
      image: (new Gtk.Image ({icon_name: 'emblem-synchronizing-symbolic'})),
      tooltip_text: _("Refresh the stream"),
    })));
    
    this.refresh_btn.get_style_context ().add_class ("image-button");
    
    this.headerbar.pack_end ((this.user_menu_btn = new UserButton.UserButton ({
      image: (new Gtk.Image ({icon_name: 'mail-send-symbolic'})),
      tooltip_text: _("Switch and manage users"),
      popover: (this.user_menu = new UserMenu.UserMenu ()),
    })));
    
  },
  
  _save_settings: function () {
    let allocation = this.window.get_allocation ();
    this.settings.set_setting ("ui.h", allocation.height);
    this.settings.set_setting ("ui.w", allocation.width);
    
    let win_pos = this.window.get_position ();
    this.settings.set_setting ("ui.x", win_pos[0]);
    this.settings.set_setting ("ui.y", win_pos[1]);
    this.settings.commit_to_file ();
  }
  
});
