import {Model} from './Model';

export interface IDatabaseColumn {
    id?: number;
    headerName: string;
    field: string;
    DatabaseId: string;
    UUID: string;
    Type: string;
    additionalData: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;
}

export class DatabaseColumn extends Model<IDatabaseColumn> implements IDatabaseColumn {
    id?: number;
    headerName: string;
    field: string;
    DatabaseId: string;
    UUID: string;
    Type: string;
    additionalData: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;

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

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

    constructor(
        headerName: string,
        field: string,
        DatabaseId: string,
        UUID: string,
        Type: string,
        additionalData: string,
        needsServerUpdate?: boolean,
        deleted?: boolean,
        offlineUpdatedAt?: string,
        id?: number,
    ) {
        super();

        this.headerName = headerName;
        this.field = field;
        this.DatabaseId = DatabaseId;
        this.UUID = UUID;
        this.Type = Type;
        this.additionalData = additionalData;

        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.headerName = record.headerName;
        this.field = record.field;
        this.DatabaseId = record.DatabaseId;
        this.UUID = record.UUID;
        this.Type = record.Type;
        this.additionalData = record.additionalData;
    }

    public getSaveRecord(): any {
        return {
            ...(this.id ? { id: this.id } : {}),
            headerName: this.headerName,
            field: this.field,
            DatabaseId: this.DatabaseId,
            UUID: this.UUID,
            Type: this.Type,
            additionalData: this.additionalData,
            ...(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<IDatabaseColumn, number> {
        return this.staticClass().dbService.table('databaseColumns') as Dexie.Table<IDatabaseColumn, number>;
    }
}
