import ngModule from '../module';
import SearchPanel from 'core/components/searchbar/search-panel';

class Controller extends SearchPanel {
    constructor($element, $) {
        super($element, $);
        let model = 'Item';
        let moreFields = ['id', 'description', 'name', 'isActive'];

        let properties;
        let validations = window.validations;

        if (validations && validations[model])
            properties = validations[model].properties;
        else
            properties = {};

        this.moreFields = [];
        for (let field of moreFields) {
            let prop = properties[field];
            this.moreFields.push({
                name: field,
                label: prop ? prop.description : field,
                type: prop ? prop.type : null
            });
        }
    }

    get filter() {
        let filter = this.$.filter;

        for (let fieldFilter of this.fieldFilters)
            filter[fieldFilter.name] = fieldFilter.value;

        return filter;
    }

    set filter(value) {
        if (!value)
            value = {};
        if (!value.tags)
            value.tags = [{}];

        this.fieldFilters = [];
        for (let field of this.moreFields) {
            if (value[field.name] != undefined) {
                this.fieldFilters.push({
                    name: field.name,
                    value: value[field.name],
                    info: field
                });
            }
        }

        this.$.filter = value;
    }

    removeField(index, field) {
        this.fieldFilters.splice(index, 1);
        delete this.$.filter[field];
    }
}

ngModule.vnComponent('vnItemSearchPanel', {
    template: require('./index.html'),
    controller: Controller
});