import { Component, Input, ChangeDetectionStrategy, Output, EventEmitter } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';

import { SearchMeta } from '../store/model';
import { Attribute } from 'src/app/metamodel/model';

interface ModalData {
    isOpen: boolean;
    type: string;
    data: object;
}

@Component({
    selector: 'app-datatable',
    templateUrl: 'datatable.component.html',
    styleUrls: ['datatable.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DatatableComponent {
    @Input() datasetName: string;
    @Input() datasetAttributeList: Attribute[];
    @Input() searchMeta: SearchMeta;
    @Input() searchData: any[];
    @Output() initSearchMeta: EventEmitter<{}> = new EventEmitter();
    @Output() getSearchData: EventEmitter<number> = new EventEmitter();

    bsModalRef: BsModalRef;

    modalData: ModalData = {
        isOpen: false,
        type: null,
        data: null
    };

    initDatatable() {
        this.initSearchMeta.emit();
        this.getSearchData.emit(1);
    }

    getAttributeRenderer(attributeName: string): string {
        const attribute = this.datasetAttributeList.find(a => a.name === attributeName);
        return attribute.renderer;
    }

    getAttributeUriAction(attributeName: string, datum: string): string {
        const attribute = this.datasetAttributeList.find(a => a.name === attributeName);
        return attribute.uri_action;
    }

    openModal(type: string, attributeName: string, value: string) {
        this.modalData.type = type;
        if (type === 'thumbnail') {
            this.modalData.data = {
                title: value,
                srcImage: this.getAttributeUriAction(attributeName, value)
            };
        } else if (type === 'fancybox') {
            this.modalData.data = {
                title: value,
                idAttribute: value,
            };
        }
        this.modalData.isOpen = true;
    }

    closeModal(event: null) {
        this.modalData.isOpen = false;
        this.modalData.type = null;
        this.modalData.data = null;
    }
}