#!/usr/bin/gjs

const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Gdkpixbuf = imports.gi.GdkPixbuf;
const Lang = imports.lang;
const Dig = imports.gi.DiscidentGlib;

var COLS = {
	Barcode : {value: 0, name: "Barcode", type: GObject.TYPE_STRING },
	Description : {value: 1, name: "Description", type: GObject.TYPE_STRING},
	Cover : {value: 2, name: "Cover", type: Gdkpixbuf.GdkPixbuf}
};

const Liesadur = new Lang.Class({
    Name: 'Liesadur',

    _init: function() {
        this.application = new Gtk.Application({
            application_id: 'org.gnome.Liesadur'
        });

    this.application.connect('activate', Lang.bind(this, this._onActivate));
    this.application.connect('startup', Lang.bind(this, this._onStartup));
    this.application.connect('shutdown', Lang.bind(this, this._onShutdown));
    },

    _onActivate: function() {
        this._window.present();
    },

    _onStartup: function() {
        this._buildUI ();
        this._loadData ();
    },

    _onShutdown: function() {
        print ("save data from the liststore to the database");
    },

    _buildUI: function() {

        this._window = new Gtk.ApplicationWindow({
            application: this.application,
            window_position: Gtk.WindowPosition.CENTER,
            default_height: 250,
            default_width: 100,
            border_width: 20,
            title: "Liesadur"});

        // Create the underlying liststore for the phonebook
        this._listStore = new Gtk.ListStore ();
        this._listStore.set_column_types ([
            COLS.Barcode.type,
            COLS.Description.type,
            COLS.Cover.type]);

        // Create the treeview
        this._treeView = new Gtk.TreeView ({
            expand: true,
            model: this._listStore });

        // Create the columns for the address book
        let description = new Gtk.TreeViewColumn ({ title: "Description" });

        // Create a cell renderer for normal text
        let normal = new Gtk.CellRendererText ();

        // Pack the cell renderers into the columns
        description.pack_start (normal, true);

        // Set each column to pull text from the TreeView's model
        description.add_attribute (normal, "text", COLS.Description.value);

        // Insert the columns into the treeview
        this._treeView.insert_column (description, -1);

        // Create the label that shows details for the name you select
        this._label = new Gtk.Label ({ label: "" });

        // Get which item is selected
        this.selection = this._treeView.get_selection();

        // When something new is selected, call _on_changed
        this.selection.connect ('changed', Lang.bind (this, this._onSelectionChanged));

        // Create a grid to organize everything in
        this._grid = new Gtk.Grid;

        // Attach the treeview and label to the grid
        this._grid.attach (this._treeView, 0, 0, 1, 1);
        this._grid.attach (this._label, 0, 1, 1, 1);

        // Add the grid to the window
        this._window.add (this._grid);

        // Show the window and all child widgets
        this._window.show_all();
    },

    _loadData: function () {
        // Create the DB directory
        let dir = GLib.get_home_dir () + "Liesadur";
        Glib.mkdir_with_parents (dir);

        this.connection = new Gda.Connection ({provider: Gda.Config.get_provider("SQLite"),
		cnc_string:"DB_DIR=" + dir + ";DB_NAME=database.sqlite"});
	this.connection.open ();

	try {
		var dm = Gda.execute_select_command (this.connection, "select * from items");
		var iter = dm.create_iter ();

		while (iter.move_next ()) {
			var barcode_field = Gda.value_stringify (iter.get_value_at (COLS.Barcode.value));
			var desc_field = Gda.value_stringify (iter.get_value_at (COLS.Description.value));

			this._listStore.set (this._listStore.append(), [COLS.Barcode.value, COLS.Description.value],
					     [barcode_field, desc_field]);
		}
		print ("<i>" + dm.get_n_rows () + " record(s)</i>");
	} catch (e) {
		Gda.execute_non_select_command (this.connection, "create table items (id integer, name varchar(100))");
	}

        // Put the data in the phonebook
        for (let i = 0; i < phonebook.length; i++ ) {
            let contact = phonebook [i];
            this._listStore.set (this._listStore.append(), [0, 1, 2],
                [contact.name, contact.surname, contact.description]);
        }
    },

    _onSelectionChanged: function () {

        // Grab a treeiter pointing to the current selection
        let [ isSelected, model, iter ] = this.selection.get_selected();

        // Set the label to read off the values stored in the current selection
        this._label.set_label ("\n" +
            this._listStore.get_value (iter, 0) + " " +
            this._listStore.get_value (iter, 1) + " " +
            this._listStore.get_value (iter, 2));
    }

});

// Run the application
let app = new Liesadur ();
app.application.run (ARGV);
