class BinaryFileContentSelector extends SelectEditor {
	
	_template = `<div class="eicui-select-editor cols-2">
        <input eicinput type="file" data-type="ignore" placeholder="Select a file" />
    </div>`;
	
    file = {
        label: '',
        content: null,
        type: ''
    }

    open() { 
        super.open();
        this.input = this.components.find(c => c.el.nodeName == 'INPUT');
        this.input.el.click();
        ui.hide(this.el)
    }

	initEvents() { 
        this.el.querySelector('input').addEventListener('change', this.onFileChange.bind(this)); 
    }   

    onFileChange(event) {
        let file = this.input.el.files[0];
        this.reader = new FileReader();
        this.reader.onload = this.onFileLoaded.bind(this);
        this.reader.readAsArrayBuffer(file);
        this.file.label = file.name;
        this.file.value = file.name;
        this.file.type = file.type;
    }
	
    onFileLoaded() { 
        this.file.content = this.arrayBufferToBase64(this.reader.result); 
        this.commit(JSON.parse(JSON.stringify(this.file)));
    }

    get value() { return this.file }

    arrayBufferToBase64( buffer ) {
        let bytes = new Uint8Array( buffer );
        let size = bytes.byteLength;
        let binary = '';
        for (let i = 0; i < size; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }
}