from gi.types import GObjectMeta
from gi.repository import GObject
from gi.repository import Gom


# Need a metaclass until we get something like _gclass_init_
#     https://bugzilla.gnome.org/show_bug.cgi?id=701843
class ItemResourceMeta(GObjectMeta):
    def __init__(cls, name, bases, dct):
        super(ItemResourceMeta, cls).__init__(name, bases, dct)
        cls.set_table("items")
        cls.set_primary_key("id")
        cls.set_notnull("name")


class ItemResource(Gom.Resource, metaclass=ItemResourceMeta):
    id = GObject.Property(type=int)
    name = GObject.Property(type=str)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)


if __name__ == '__main__':
    # Connect to the database
    adapter = Gom.Adapter()
    adapter.open_sync(":memory:")

    # Create the table
    repository = Gom.Repository(adapter=adapter)
    repository.automatic_migrate_sync(1, [ItemResource.__gtype__])  # This fails

    # Insert an item
    item = ItemResource(repository=repository, name="item1")
    item.save_sync()

    # Fetch the item back
    item = repository.find_one_sync(ItemResource, None)
    print("Item: id=%d, name='%s'" % (item.get_property('id'), item.get_property('name')))

    # Close the database
    adapter.close_sync()
