var Modules = function(){}

Modules.prototype.init = function(){
    this.initConfigCrop();
}
Modules.prototype.crooper = null;
Modules.prototype.OriginalCrooper = null;
Modules.prototype.OriginalImage = null;

/**
 * 
 */
Modules.prototype.initConfigCrop = function(){
    let scope = this;
    document.getElementById("upload").onclick = ()=>document.getElementById('inputImage').click();
    document.getElementById('inputImage').onchange = function(e) {
        var fileReader = new FileReader();
        fileReader.onload = function(event) {
          var img = document.getElementById('previewImage');
          img.src = event.target.result;
          scope.createCrooper(img);
          scope.OriginalImage = img;
          scope.OriginalCrooper = scope.crooper;
          scope.setEventButtonClick([
            ()=>scope.onDownloadImage(scope.crooper)
          ]);
        };
        fileReader.readAsDataURL(e.target.files[0]);
    };

    // Filtros originales
    document.getElementById("filter1").onclick = ()=>{ scope.applyFilter(["grayscale"]); }
    document.getElementById("filter2").onclick = ()=>{ scope.applyFilter(["sepia"]); }
    document.getElementById("filter3").onclick = ()=>{ scope.applyFilter(["invert"]); }
    document.getElementById("filter4").onclick = ()=>{ scope.applyFilter(["grayscale","invert"]); }
    document.getElementById("filter5").onclick = ()=>{ scope.applyFilter(["sepia","invert"]); }
    document.getElementById("filter6").onclick = ()=>{ scope.applyFilter(["saturate","invert"]); }

    // Nuevos filtros
    document.getElementById("filter7").onclick = ()=>{ scope.applyFilter(["brightness(1.5)"]); }
    document.getElementById("filter8").onclick = ()=>{ scope.applyFilter(["contrast(2)"]); }
    document.getElementById("filter9").onclick = ()=>{ scope.applyFilter(["blur(2px)"]); }
    document.getElementById("filter10").onclick = ()=>{
      scope.applyFilter([
        "sepia(0.3)",
        "hue-rotate(180deg)",
        "saturate(1.2)"
      ]);
    }
    document.getElementById("filter11").onclick = ()=>{
      scope.applyFilter([
        "sepia(0.4)",
        "hue-rotate(-20deg)",
        "brightness(1.1)"
      ]);
    }
    document.getElementById("filter12").onclick = ()=>{
      scope.applyFilter([
        "contrast(1.2)",
        "brightness(1.1)",
        "saturate(1.3)"
      ]);
    }

    document.getElementById("restore").onclick = ()=>{ scope.restore().then(()=>null); }
}

/**
 * 
 * @param {*} img 
 */
Modules.prototype.createCrooper = function(img){
    this.crooper = new Cropper(img, {
        aspectRatio: NaN,
        viewMode: 1,
        autoCropArea: 0,
        dragMode: 'move'
    });
}

/**
 * 
 * @param {*} callbacks 
 */
Modules.prototype.setEventButtonClick = function(callbacks){
    document.getElementById('cropButton').onclick = function() {
        callbacks.forEach(cb => cb());
    };
}

/**
 * 
 * @param {*} cropper 
 */
Modules.prototype.onDownloadImage = function(cropper){
    var canvas = cropper.getCroppedCanvas();
    canvas.toBlob(function(blob) {
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'imagen_recortada.jpg';
        link.click();
        URL.revokeObjectURL(link.href);
    }, 'image/jpeg');
}

/**
 * Aplica filtros. Ahora acepta cadenas con paréntesis (valores) o nombres simples.
 * @param {string[]} filters 
 */
Modules.prototype.applyFilter = function(filters) {
   this.restore().then(()=>{
    let canvas = document.createElement('canvas');
    let ctx = canvas.getContext('2d');
    canvas.width = this.crooper.image.naturalWidth;
    canvas.height = this.crooper.image.naturalHeight;
    // Construir la cadena filter
    let filterStr = filters.map(f => {
      // si ya trae paréntesis, úsalo tal cual
      return f.includes('(') ? f : `${f}(100%)`;
    }).join(' ');
    ctx.filter = filterStr;
    ctx.drawImage(this.crooper.image, 0, 0, canvas.width, canvas.height);
    // Reemplaza la imagen del cropper
    this.crooper.replace(canvas.toDataURL('image/jpeg'));
   });
}

Modules.prototype.restore = function(){
    return new Promise((resolve)=>{
        this.crooper.destroy();
        this.crooper = new Cropper(this.OriginalImage, {
            aspectRatio: NaN,
            viewMode: 1,
            autoCropArea: 0,
            dragMode: 'move',
            ready: () => resolve()
        });
    });
}

export default Modules;
