import ngModule from '../../module';
import Button from '../button';
import assignProps from '../../lib/assign-props';
import './style.scss';

export default class ButtonMenu extends Button {
    constructor($element, $scope, $transclude) {
        super($element, $scope);
        this.$transclude = $transclude;
        $element.on('click', e => this.onButtonClick(e));
    }

    get model() {
        return this._model;
    }

    set model(value) {
        this.dropDownAssign({model: value});
    }

    get data() {
        return this._data;
    }

    set data(value) {
        this.dropDownAssign({data: value});
    }

    get url() {
        return this._url;
    }

    set url(value) {
        this.dropDownAssign({url: value});
    }

    dropDownAssign(props) {
        for (let prop in props)
            this[`_${prop}`] = props[prop];
        if (this.$.dropDown)
            Object.assign(this.$.dropDown, props);
    }

    onButtonClick(event) {
        if (event.defaultPrevented) return;
        this.emit('open');
        this.showDropDown();
    }

    onDropDownSelect(item) {
        const value = item[this.valueField];
        this.field = value;
        this.emit('change', {value});
    }

    showDropDown() {
        this.$.dropDown.copySlot('tplItem', this.$transclude);

        assignProps(this, this.$.dropDown, [
            'valueField',
            'showField',
            'showFilter',
            'multiple',
            'translateFields',
            'model',
            'data',
            'url',
            'fields',
            'include',
            'where',
            'order',
            'limit',
            'searchFunction'
        ]);
        this.$.dropDown.show(this.element);
    }
}
ButtonMenu.$inject = ['$element', '$scope', '$transclude'];

ngModule.vnComponent('vnButtonMenu', {
    template: require('./index.html'),
    controller: ButtonMenu,
    bindings: {
        showField: '@?',
        selection: '<?',
        valueField: '@?',
        selectFields: '<?',
        initialData: '<?',
        showFilter: '<?',
        fields: '<?',
        field: '=?',
        url: '@?',
        data: '<?',
        where: '@?',
        order: '@?',
        limit: '<?',
        multiple: '<?',
        onChange: '&?',
        translateFields: '<?',
        onOpen: '&?'
    },
    transclude: {
        tplItem: '?tplItem'
    }
});