import {Model} from './Model';

export interface IDatabase {
    id?: number;
    Name: string;
    NodeId: string;
    PageId: string;
    ColumnIds: string[];
    UUID: string;
    Active: boolean;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;
}

export class Database extends Model<IDatabase> implements IDatabase {
    id?: number;
    Name: string;
    NodeId: string;
    PageId: string;
    ColumnIds: string[];
    UUID: string;
    Active: boolean;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;

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

    public static getSchema() {
        return '++id, Name, NodeId, PageId, ColumnIds, UUID, Active, needsServerUpdate, deleted, offlineUpdatedAt';
    }

    constructor(
        Name: string,
        NodeId: string,
        PageId: string,
        ColumnIds: string[],
        UUID: string,
        Active: boolean,
        needsServerUpdate?: boolean,
        deleted?: boolean,
        offlineUpdatedAt?: string,
        id?: number,
    ) {
        super();

        this.Name = Name;
        this.NodeId = NodeId;
        this.PageId = PageId;
        this.ColumnIds = ColumnIds;
        this.UUID = UUID;
        this.Active = Active;

        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.Name = record.Name;
        this.NodeId = record.NodeId;
        this.PageId = record.PageId;
        this.ColumnIds = record.ColumnIds;
        this.UUID = record.UUID;
        this.Active = record.Active;
    }

    public getSaveRecord(): any {
        return {
            ...(this.id ? { id: this.id } : {}),
            Name: this.Name,
            NodeId: this.NodeId,
            PageId: this.PageId,
            ColumnIds: this.ColumnIds,
            UUID: this.UUID,
            Active: this.Active,
            ...(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<IDatabase, number> {
        return this.staticClass().dbService.table('databases') as Dexie.Table<IDatabase, number>;
    }
}
