﻿using Jarvis.Server.Interfaces;
using SQLite.Net.Attributes;
using System;
using static Jarvis.Server.Data.Enums;

namespace Jarvis.Server.Data.Persistent
{
    public abstract class AbstractDatabaseObject : IDatabaseObject, IDeserializable
    {
        protected static Database db = Database.Instance;
        protected static Loggerino log = Loggerino.Instance;
        private string id = null;

        [PrimaryKey]
        public string Id
        {
            get
            {
                if (id == null)
                    id = Guid.NewGuid().ToString();
                return id;
            }
            set { id = value; }
        }

        public AbstractDatabaseObject()
        {
        }

        public static T GetById<T>(string id)
        {
            lock (db)
            {
                return (T)db.Find(id, db.GetMapping<T>());
            }
        }

        virtual public bool Delete()
        {
            try
            {
                lock (db)
                {
                    if (db.Delete(this) > 0)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception e)
            {
                log.E(LogCategory.Database, e, "deletion of database object failed");
                return false;
            }
        }

        virtual public bool Insert()
        {
            try
            {
                lock (db)
                {
                    Id = Guid.NewGuid().ToString();
                    if (db.Insert(this) > 0)
                        return true;
                    else
                        return true;
                }
            }
            catch (Exception e)
            {
                log.E(LogCategory.Database, e, "insertion of database object failed");
                return false;
            }
        }

        virtual public bool Update()
        {
            try
            {
                lock (db)
                {
                    if (db.Update(this) > 0)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception e)
            {
                log.E(LogCategory.Database, e, "updating database object failed");
                return false;
            }
        }
    }
}