import ngModule from '../../module';
import Field from '../field';
import './style.scss';

/**
 * Input file selector.
 *
 * @property {String} accept List of valid file types
 */
export default class InputFile extends Field {
    constructor($element, $) {
        super($element, $);
        this._multiple = false;
        this.input = this.element.querySelector('input');
        this.registerEvents();
    }

    /*
     * Registers all event emitters
     */
    registerEvents() {
        this.input.addEventListener('change', () => {
            const files = this.input.files;
            const fileList = Array
                .from(files)
                .map(file => file.name)
                .join(', ');

            const label = this.element.querySelector('.value');
            label.innerHTML = fileList;

            this.field = files.length ? files : null;
        });
    }

    get field() {
        return super.field;
    }

    set field(value) {
        if (!value) this.input.value = '';
        super.field = value;
    }

    /**
     * @property {FileList} files Selected files list
     */
    get files() {
        return this.input.files;
    }

    set files(value) {
        this.input.files = value;
    }

    /**
     * @property {Boolean} multiple Whether to allow multiple file selection
     */
    get multiple() {
        return this.input.multiple;
    }

    set multiple(value) {
        this.input.multiple = value;
    }

    /*
     * Fires file selection explorer event
     */
    openFileSelector() {
        this.input.click();
    }

    onChange($event) {
        this.emit('change', {
            value: this.field,
            $files: this.files,
            $event: $event
        });
    }

    get accept() {
        return this._accept;
    }

    set accept(value) {
        this._accept = value;
        this.$.$applyAsync(() =>
            this.input.setAttribute('accept', value));
    }
}

ngModule.vnComponent('vnInputFile', {
    template: require('./index.html'),
    controller: InputFile,
    bindings: {
        multiple: '<?',
        accept: '@?',
        files: '=?'
    }
});