import {Model} from './Model';

export interface IDatabaseEntry {
    id?: number;
    DatabaseId: string;
    RowDataJSON: string;
    UUID: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;
}

export class DatabaseEntry extends Model<IDatabaseEntry> implements IDatabaseEntry {
    id?: number;
    DatabaseId: string;
    RowDataJSON: string;
    UUID: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;

    public static getTableName() {
        return 'databaseEntries';
    }

    public static getSchema() {
        return '++id, [DatabaseId+UUID], RowDataJSON, needsServerUpdate, deleted, offlineUpdatedAt';
    }

    constructor(
        DatabaseId: string,
        UUID: string,
        RowDataJSON: string,
        needsServerUpdate?: boolean,
        deleted?: boolean,
        offlineUpdatedAt?: string,
        id?: number,
    ) {
        super();

        this.DatabaseId = DatabaseId;
        this.RowDataJSON = RowDataJSON;
        this.UUID = UUID;

        if ( typeof needsServerUpdate !== 'undefined' ) {
            this.needsServerUpdate = needsServerUpdate;
        }

        if ( typeof deleted !== 'undefined' ) {
            this.deleted = deleted;
        }

        if ( typeof offlineUpdatedAt !== 'undefined' ) {
            this.offlineUpdatedAt = offlineUpdatedAt;
        }

        if ( id ) {
            this.id = id;
        }
    }

    public fillFromRecord(record: any) {
        this.DatabaseId = record.DatabaseId;
        this.RowDataJSON = JSON.stringify(record.RowData);
        this.UUID = record.UUID;
    }

    public inflateToRecord() {
        const record = this.getSaveRecord();
        record.RowData = record.RowDataJSON ? JSON.parse(record.RowDataJSON) : {};
        delete record.RowDataJSON;
        return record;
    }

    public getSaveRecord(): any {
        return {
            ...(this.id ? { id: this.id } : {}),
            DatabaseId: this.DatabaseId,
            RowDataJSON: this.RowDataJSON,
            UUID: this.UUID,
            ...(typeof this.needsServerUpdate === 'undefined' ? {} : { needsServerUpdate: this.needsServerUpdate }),
            ...(typeof this.deleted === 'undefined' ? {} : { deleted: this.deleted }),
            ...(typeof this.offlineUpdatedAt === 'undefined' ? {} : { offlineUpdatedAt: this.offlineUpdatedAt })
        };
    }

    public getDatabase(): Dexie.Table<IDatabaseEntry, number> {
        return this.staticClass().dbService.table('databaseEntries') as Dexie.Table<IDatabaseEntry, number>;
    }
}
