import Dexie from 'dexie';
import {DatabaseService} from './database.service';
import {uuid_v4} from '../../utility';

export abstract class Model<InterfaceType> {
    public static dbService?: DatabaseService;

    public id?: number;

    public static getSchema(): string {
        throw new TypeError('Child class must implement.');
    }

    public static getTableName(): string {
        throw new TypeError('Child class must implement.');
    }

    public static getUUID(): string {
        return uuid_v4();
    }

    public abstract getDatabase(): Dexie.Table<InterfaceType, number>;
    public abstract getSaveRecord(): any;

    public staticClass() {
        return (this.constructor as typeof Model);
    }

    public exists() {
        return !!this.id;
    }

    public async save() {
        const record = this.getSaveRecord();

        for ( const prop in record ) {
            if ( !record.hasOwnProperty(prop) ) {
                continue;
            }

            if ( [true, false].includes(record[prop]) ) {
                record[prop] = record[prop] ? 1 : 0;
            }
        }

        record.offlineUpdatedAt = String(new Date());

        this.id = await this.getDatabase().put(record);
    }
}
