import {Component, Input, OnInit} from '@angular/core';
import {AlertController, ModalController} from '@ionic/angular';
import {EditorService} from '../../../service/editor.service';
import {debug} from '../../../utility';
import {NodeTypeIcons} from '../../../structures/node-types';
import {Database, DatabaseColumn} from '../../../structures/db-api';
import {DbApiService} from '../../../service/db-api.service';
import HostRecord from '../../../structures/HostRecord';

export interface FormDatabaseMap {
    formNodeId?: string;
    databaseColumnId?: string;

    formNode?: any;
    databaseColumn?: DatabaseColumn;
}

@Component({
    selector: 'noded-form-database-link',
    templateUrl: './database-link.component.html',
    styleUrls: ['./database-link.component.scss'],
})
export class DatabaseLinkComponent implements OnInit {
    @Input() pageId: string;
    @Input() editorUUID: string;

    public readonly typeIcons = NodeTypeIcons;
    public databases: Database[] = [];
    public selectedDatabase?: Database;
    public selectedDatabaseColumns: DatabaseColumn[] = [];
    public mapping: FormDatabaseMap[] = [];
    public formFields: any[] = [];

    constructor(
        protected alerts: AlertController,
        protected modals: ModalController,
        protected editorService: EditorService,
        protected dbApi: DbApiService,
    ) {}

    async ngOnInit() {
        debug('Database link component', this);
        this.editorService = this.editorService.getEditor(this.editorUUID);

        this.databases = await this.dbApi.getDatabases();

        this.formFields = this.editorService.immutableNodes
            .filter(x => x.isForm())
            .map(x => {
                const data = {...x.AdditionalData};
                data.NodeId = x.UUID;
                return data;
            });

        const meta = this.editorService.metadata;
        if ( meta?.formDatabaseId ) {
            this.selectedDatabase = this.databases.find(x => x.uuid === meta.formDatabaseId);
            await this.onDatabaseChange();
        }

        if ( Array.isArray(meta?.formMapping) ) {
            this.mapping = meta.formMapping.map(x => {
                return {
                    formNode: this.formFields.find(field => field.NodeId === x.formNodeId),
                    databaseColumn: this.selectedDatabaseColumns.find(column => column.uuid === x.databaseColumnId),
                };
            });
        }
    }

    onAddMappingClick(event) {
        this.mapping.push({} as FormDatabaseMap);
    }

    async onDatabaseChange() {
        this.mapping = [];
        this.selectedDatabaseColumns = await this.selectedDatabase.columns();
    }

    onMappingDelete(item) {
        this.mapping = this.mapping.filter(x => x !== item);
    }

    dismiss(save = false) {
        if ( save ) {
            const merge = {
                formDatabaseId: this.selectedDatabase?.uuid,
                formMapping: this.mapping.map(x => {
                    return {
                        formNodeId: x.formNode?.NodeId || x.formNodeId,
                        databaseColumnId: x.databaseColumn?.uuid || x.databaseColumnId,
                    };
                }),
            };

            this.editorService.metadata = {
                ...this.editorService.metadata,
                ...merge,
            };

            this.editorService.triggerSave();
        }

        this.modals.dismiss();
    }
}
