#!/usr/bin/gjs

const Lang = imports.lang;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const GIRepository = imports.gi.GIRepository;
const Gom = imports.gi.Gom;
const Mainloop = imports.mainloop;

const INT32_MAX = (2147483647);

const ItemClass = new Lang.Class({
    Name: 'Item',
    Extends: Gom.Resource,

    Properties: {
        'id':  GObject.ParamSpec.int('id', 'ID',
                                     'An ID', GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT,
                                     0, INT32_MAX, 0),
        'url': GObject.ParamSpec.string('url', 'URL',
					'A URL',
					GObject.ParamFlags.READABLE | GObject.ParamFlags.WRITABLE | GObject.ParamFlags.CONSTRUCT,
					''),
    },

    _init: function(params) {
        this.parent(params);

        Gom.Resource.set_table.call(this, 'items');
        Gom.Resource.set_primary_key.call(this, 'id');
    },

    _instance_init: function() {
    },
});

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

    _init: function() {
        this._adapter = new Gom.Adapter;
        this._adapter.open_async('/tmp/test.db', this._onAdapterOpened.bind(this));
    },

    _onAdapterOpened: function(adapter, result) {
        try {
            if (adapter.open_finish(result)) {
              let repo = new Gom.Repository({
                  adapter: adapter,
              });
              repo.automatic_migrate_async(1, [ ItemClass ], this._onMigrate.bind(this));
            }
        } catch (e) {
            log(e);
        }
    },

    _onMigrate: function(repository, result) {
        try {
            let success = repository.automatic_migrate_finish(result);
            if (success) {
                this._adapter.close_sync();
            }
        } catch(e) {
            log(e);
        }
    },
});

let myclass = new MyClass();
Mainloop.run();
