import {Model} from './Model';

export interface IFileGroup {
    id?: number;
    NodeId: string;
    PageId: string;
    FileIds: string[];
    filesJSON: string;
    UUID: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;
}

export class FileGroup extends Model<IFileGroup> implements IFileGroup {
    id?: number;
    NodeId: string;
    PageId: string;
    FileIds: string[];
    filesJSON: string;
    UUID: string;
    needsServerUpdate?: boolean;
    deleted?: boolean;
    offlineUpdatedAt?: string;

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

    public static getSchema() {
        return '++id, NodeId, PageId, FileIds, filesJSON, UUID, needsServerUpdate, deleted, offlineUpdatedAt';
    }

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

        this.NodeId = NodeId;
        this.PageId = PageId;
        this.FileIds = FileIds;
        this.filesJSON = filesJSON;
        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.NodeId = record.NodeId;
        this.PageId = record.PageId;
        this.FileIds = record.FileIds;
        this.filesJSON = JSON.stringify(record.files);
        this.UUID = record.UUID;
    }

    public inflateToRecord() {
        return {
            NodeId: this.NodeId,
            PageId: this.PageId,
            FileIds: this.FileIds,
            files: JSON.parse(this.filesJSON),
            UUID: this.UUID,
        };
    }

    public getSaveRecord(): any {
        return {
            ...(this.id ? { id: this.id } : {}),
            NodeId: this.NodeId,
            PageId: this.PageId,
            FileIds: this.FileIds,
            filesJSON: this.filesJSON,
            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<IFileGroup, number> {
        return this.staticClass().dbService.table('fileGroups') as Dexie.Table<IFileGroup, number>;
    }
}
