/**
 * This file is part of Anis Client.
 *
 * @copyright Laboratoire d'Astrophysique de Marseille / CNRS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

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

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

import { Attribute } from 'src/app/metamodel/models';
import { Column } from 'src/app/admin/store/models';

@Component({
    selector: 'app-add-attribute',
    templateUrl: 'add-attribute.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class AddAttributeComponent {
    @Input() columnList: Column[];
    @Input() columnListIsLoading: boolean;
    @Input() columnListIsLoaded: boolean;
    @Input() attributeList: Attribute[];
    @Output() loadColumnList: EventEmitter<{}> = new EventEmitter();
    @Output() add: EventEmitter<Attribute> = new EventEmitter();

    modalRef: BsModalRef;

    constructor(private modalService: BsModalService) { }

    openModal(template: TemplateRef<any>) {
        this.loadColumnList.emit();
        this.modalRef = this.modalService.show(template);
    }

    alreadyExists(columnName: string): boolean {
        return this.attributeList.map(a => a.name).includes(columnName);
    }

    addNewAttribute(column: Column) {
        let id = 1;
        if (this.attributeList.length > 0) {
            id = Math.max(...this.attributeList.map(a => a.id)) + 1;
        }
        
        this.add.emit({
            id,
            name: column.name,
            label: column.name,
            form_label: column.name,
            description: null,
            primary_key: false,
            type: column.type,
            search_type: null,
            operator: null,
            dynamic_operator: null,
            min: null,
            max: null,
            placeholder_min: null,
            placeholder_max: null,
            criteria_display: id * 10,
            output_display: id * 10,
            selected: true,
            renderer: null,
            renderer_config: null,
            order_by: true,
            archive: false,
            detail_display: id * 10,
            options: null,
            vo_utype: null,
            vo_ucd: null,
            vo_unit: null,
            vo_description: null,
            vo_datatype: null,
            vo_size: null,
            id_criteria_family: null,
            id_output_category: null,
            id_detail_output_category: null
        })
    }
}