const UploadFile = (function () {
    const init = (id, properties) => {

        let defProperties = {
            extensions: ['*'],
            selectButton:  {
                text: 'Seleccionar fichero',
                icon: 'mdi mdi-plus',
                class: 'btn-material-primary-high-emphasis'
            },       
            uploadButton: {
                text: 'Subir',
                icon: 'mdi mdi-upload',
                class: 'btn-material-primary-high-emphasis'
            },
            cancelButton: {
                text: 'Cancelar',
                icon: 'mdi mdi-close-circle',
                class: 'btn-material-secondary-high-emphasis'
            },
            submitInForm: false,
            url: "#",
            data: () => {} ,
            start: (e, data) => {console.log("start");},
            done: (e, data) => {console.log("done");},
            fail: (e, data) => {console.log("fail");},
        }

       const extend = (...args) => {
            return args.reduce((acc, x) => {
                let key = '';
                for (key in x) {
                    acc[key] = x[key];
                }
                return acc;
            }, {});
        };

        defProperties = extend(defProperties, properties);

        const input = document.getElementById(id);
        input.setAttribute('accept', defProperties.extensions.join(',') );
        input.setAttribute('style', "display: none;" );

        const uploadLayer = document.createElement("div");
        uploadLayer.setAttribute('id', `uploadFile_${id}_layer`);
        let html = "";
        if(!defProperties.submitInForm) {
            html += `<form id="uploadFile_${id}_form" enctype="multipart/form-data" method="POST" action="${defProperties.url}">`;
        }
        html += `
                <div class="form-row">
                    <div class="col-md-12 ">
                        <div class="rup-upload">
                            <span id="uploadFile_${id}_button" class="btn btn-material fileinput-button ${defProperties.selectButton.class}">
                                <i class="${defProperties.selectButton.icon}"></i>
                                <span>${defProperties.selectButton.text}</span>
                            </span>
                        
                            <div class="fileupload-content">
                                <div class="files list-group" id="uploadFile_${id}_listGroup"></div>
                            </div>
                        </div>
                    </div>
                </div>
         `;
            
        if(!defProperties.submitInForm) {
            html += `</form>`;
        }
        uploadLayer.innerHTML = html;
        
        // Borramos la capa por si ya existe la capa
        try{
        	document.getElementById(`uploadFile_${id}_layer`).remove();
        }catch(err){}
        
        input.after(uploadLayer);

        // Capturar el click
        const button = document.getElementById(`uploadFile_${id}_button`);
        button.addEventListener('click', () => {

            input.click();
        });

        // Captura change del input
        input.addEventListener('change', fileInputChange, false);

        function fileInputChange (evt) {
            for (let file of evt.target.files) {
                read(file)
            }
        }

        async function read(file) {

            const list = document.getElementById(`uploadFile_${id}_listGroup`);
            let html = `<div class="row">
                <div class="col-xs-12 col-sm-6">
                    <p class="name text-xs-left" style="width: 100%;margin-bottom: 1rem;">
                    	<b>${file.name}</b> (${_sizeOf(file.size)})
                    </p>                    
                </div>
                <div class="col-xs-12 fileupload-buttonbar col-sm-6 text-right">
            `; 
            
            if(!defProperties.submitInForm) {
            	html += `<button id="uploadFile_${id}_start" class="btn-material ${defProperties.uploadButton.class} start fileinput-button">
                            <i class="${defProperties.uploadButton.icon}" aria-hidden="true"></i>
                            <span>${defProperties.uploadButton.text}</span>
                        </button>
                `; 
            }

            html += ` <button id="uploadFile_${id}_cancel" class="btn-material ${defProperties.cancelButton.class} start fileinput-button">
                            <i class="${defProperties.cancelButton.icon}" aria-hidden="true"></i>
                            <span>${defProperties.cancelButton.text}</span>
                        </button>
                </div>
        
            </div>`; 
            list.innerHTML = html
            
            const start = document.getElementById(`uploadFile_${id}_start`);
            start.addEventListener('click',async (e) => {
            	e.preventDefault();
                e.stopPropagation();
                defProperties.start();
                await uploadFile().then(
                	async (response) => {
            			if(response.ok) {
            				defProperties.done(response);
            			}else{
            				const data =await response.json();
            				defProperties.fail(data);
            			}                			
            		}
               )
            });

            const uploadFile = async () => {
                let formData = new FormData(); 
                formData.append(`${id}`, input.files[0]);
                const params = defProperties.data();
                if(params != null && Object.keys(params).length > 0){                	
                	for (const key of Object.keys(params)) {
                		//formData.append(key, JSON.stringify(params[key]));
                		formData.append(key, params[key]);
                	}
                }
                  
                const resp = await fetch(`${defProperties.url}`, {
                    method: "POST",    
                    body: formData
                  }).catch(handleError);
                
                return resp;                
            }
            
            const handleError = function (err) {
            	console.warn(err);
            	return new Response(JSON.stringify({
            		code: 400,
            		ok: false,
            		message: 'Error'
            	}));
            };


            const cancel = document.getElementById(`uploadFile_${id}_cancel`);
            cancel.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const file = document.getElementById(id);
                file.value = '';
                list.innerHTML = '';
            });

        }

        const _sizeOf = (bytes) => {
            if (bytes == 0) { return "0.00 B"; }
            var e = Math.floor(Math.log(bytes) / Math.log(1024));
            return (bytes/Math.pow(1024, e)).toFixed(2)+' '+' KMGTP'.charAt(e)+'B';
        }

    }

    const reset = (id) => {
        const file = document.getElementById(id);
        const list = document.getElementById(`uploadFile_${id}_listGroup`);
        file.value = '';
        list.innerHTML = '';
    }
    
    const disabled = (id, disable) => {
    	const input = document.getElementById(id);
    	const button = document.getElementById(`uploadFile_${id}_button`);
    	input.disabled = disable;
    	if(disable) {
    		button.classList.add('disabled');
    	}else {
    		button.classList.remove('disabled');
    	}
    }

    return {
        init,
        reset,
        disabled
    }
})();