const dropArea=document.querySelector(".drop-area");
const dragText=dropArea.querySelector("h2");
const button=dropArea.querySelector("button");
const input=dropArea.querySelector("#input-file");
let files;

function simula_inputfile(idInput){
    document.getElementById(idInput).click();
}

input.addEventListener("change",(e)=>{
    files= this.files;
    dropArea.classList.add("active");
    showFiles(files);
    dropArea.classList.remove("active");
})

dropArea.addEventListener("dragover",(e)=>{
    e.preventDefault();
    dropArea.classList.add("active");
    dragText.textContent="Suelta para subir imagenes"
})
dropArea.addEventListener("dragleave",(e)=>{
    e.preventDefault();
    dropArea.classList.remove("active");
    dragText.textContent="Arrastra y suelta imagenes"
})
dropArea.addEventListener("drop",(e)=>{
    e.preventDefault();
    files=e.dataTransfer.files;
    showFiles(files);
    dropArea.classList.remove("active");
    dragText.textContent="Arrastra y suelta imagenes"
})
function showFiles(files){
    if(files.length === undefined){
        processFile(files);
    }else{
        for (const file of files){
            processFile(file);
        }  
    }
}

function readFile(input) {
    console.log(input)
    let file = input.files[0];
  
    let reader = new FileReader();
  
    reader.readAsText(file);
  
    reader.onload = function() {
      console.log(reader.result);
    };
  
    reader.onerror = function() {
      console.log(reader.error);
    };
  
  }

function processFile(file){
    const docType=file.type;
    const validaExtensions=['image/jpeg','image/jpg','image/png','image/gif']
    if(validaExtensions.includes(docType)){
        console.log(file)
        const fileReader = new FileReader();
        const id='file-${Math.random().toString(32).substring(7)}';

        fileReader.addEventListener("load", (e) => {
            const fileUrl=fileReader.result;
            const image=`
                <div id="${id}" class="file-container">
                    <img src="${fileUrl}" alt="${file.name}" width="50">
                    <div class="status">
                        <span>${file.name}</span>
                        <span class="status-text">
                            Loading...
                        </span>
                    </div>
                </div>
            `;
            const html=document.querySelector("#preview").innerHTML;
            document.querySelector("#preview").innerHTML=image+html;
        });
 
        fileReader.readAsDataURL(file);
        uploadFile(file,id);
    }else{
        alert("No es un archivo valido"); 
    }
}

function uploadFile(file,id){
    const XHR= new XMLHttpRequest();
    //var file = _(Idarchivo).files[0];
   console.log(file)
   console.log(file.name+" | "+file.size+" | "+file.type)
   //alert(file)
      //alert(file.name+" | "+file.size+" | "+file.type);
   var formdata = new FormData();
   formdata.append("archivos", file);
   formdata.append("empresa",VGempresa.toLowerCase());
   formdata.append("ruta","varios");
   formdata.append("modulo",sessionStorage.getItem('modulo').toLowerCase());
   formdata.append("tipo",sessionStorage.getItem('tipo'));
console.log(VGempresa.toLowerCase()+" | "+sessionStorage.getItem('modulo').toLowerCase()+" | "+sessionStorage.getItem('tipo'))
   if(sessionStorage.getItem('tipo')=="p" || sessionStorage.getItem('tipo')=="d"){//Para que se cree una sucarpeta
       //console.log(document.getElementById('c0').value)
       formdata.append("ide",file.name);
   }
    var ajax = new XMLHttpRequest();
     ajax.upload.addEventListener("progress", progressHandler, false);
      ajax.addEventListener("load", completeHandler, false);
      ajax.addEventListener("error", errorHandler, false);
      ajax.addEventListener("abort", abortHandler, false);
   //console.log(formdata);
      ajax.open("POST", "subir.php");
      ajax.send(formdata);
    XHR.onreadystatechange=function(){
        console.log(this.responseText)
    }
}
function _(el){
    return document.getElementById(el);
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
  var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
 _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
 _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}