import {DbApiService} from '../service/db-api.service';

let privDbApi!: DbApiService;
export function _setDbApi(dbApi: DbApiService) {
    privDbApi = dbApi;
}

export function _getDbApi(): DbApiService {
    return privDbApi;
}

export class Database {
    public name!: string;
    public uuid!: string;
    public pageId!: string;
    public columnIds: string[] = [];
    public versionNum?: number;

    static async all() {
        return _getDbApi().getDatabases();
    }

    static async one(databaseId: string) {
        return _getDbApi().getDatabase(databaseId);
    }

    constructor(record?: any) {
        if ( record ) {
            this.loadFrom(record);
        }
    }

    loadFrom(record: any) {
        this.name = record.name;
        this.uuid = record.uuid;
        this.pageId = record.page_id;
        this.columnIds = record.column_ids;

        if ( record.version_num ) {
            this.versionNum = record.version_num;
        }
    }

    async columns() {
        const order = await this.columnOrder();
        const columns = await _getDbApi().getColumns(this.uuid);

        return order.map(x => columns.find(col => col.uuid === x));
    }

    async columnOrder() {
        return _getDbApi().getColumnOrder(this.uuid);
    }

    async data() {
        return _getDbApi().getData(this.uuid);
    }

    async record(id: string) {
        return _getDbApi().getDataRecord(this.uuid, id);
    }
}

export class DatabaseColumn {
    public name!: string;
    public databaseId!: string;
    public uuid!: string;
    public type!: string;
    public field!: string;
    public metadata: any;

    constructor(record?: any) {
        if ( record ) {
            this.loadFrom(record);
        }
    }

    loadFrom(record: any) {
        this.name = record.name;
        this.databaseId = record.database_id;
        this.uuid = record.uuid;
        this.type = record.type;
        this.field = record.field;
        this.metadata = record.metadata;
    }
}

export class DatabaseRecord {
    public data: any = {};
    public uuid!: string;
    public databaseId!: string;

    constructor(record?: any) {
        if ( record ) {
            this.loadFrom(record);
        }
    }

    loadFrom(record: any) {
        this.data = record.data;
        this.uuid = record.uuid;
        this.databaseId = record.database_id;
    }
}
