import { Component, Input, ChangeDetectionStrategy, Output, EventEmitter } from '@angular/core';

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

@Component({
    selector: 'app-datatable',
    templateUrl: 'datatable.component.html',
    styleUrls: ['datatable.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DatatableComponent {
    @Input() datasetName: string;
    @Input() datasetList: Dataset[];
    @Input() queryParams: SearchQueryParams;
    @Input() datasetAttributeList: Attribute[];
    @Input() searchMeta: SearchMeta;
    @Input() searchData: any[];
    @Input() selectedData: any[];
    @Input() processWip: boolean;
    @Input() processDone: boolean;
    @Input() processId: string;
    @Output() initSearchMeta: EventEmitter<{}> = new EventEmitter();
    @Output() getSearchData: EventEmitter<number> = new EventEmitter();
    @Output() addSelectedData: EventEmitter<any> = new EventEmitter();
    @Output() deleteSelectedData: EventEmitter<any> = new EventEmitter();
    @Output() executeProcess: EventEmitter<string> = new EventEmitter();

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

    getDataset() {
        return this.datasetList.find(dataset => dataset.name === this.datasetName);
    }

    getAttributeId(attributeName: string): number {
        const attribute = this.datasetAttributeList.find(a => a.name === attributeName);
        return attribute.id;
    }

    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);
        if (attribute.uri_action) {
            return attribute.uri_action + datum;
        } else {
            return datum;
        }
    }

    toggleSelection(datum: any): void {
        const attribute = this.datasetAttributeList.find(a => a.search_flag === 'ID');

        const index = this.selectedData.indexOf(datum[attribute.label]);
        if (index > -1) {
            this.deleteSelectedData.emit(datum[attribute.label]);
        } else {
            this.addSelectedData.emit(datum[attribute.label]);
        }
    }

    isSelected(datum: any): boolean {
        const attribute = this.datasetAttributeList.find(a => a.search_flag === 'ID');

        if (this.selectedData.indexOf(datum[attribute.label]) > -1) {
            return true;
        }
        return false;
    }

    noSelectedData() {
        return this.selectedData.length < 1;
    }

    fireProcess(typeProcess: string): void {
        this.executeProcess.emit(typeProcess);
    }
}