var upload = function () {};


upload.onpenFile = function (control)
{
    upload.id = control.dataset.id;
    var fileUpload = document.getElementById("fileUpload-" + upload.id);

    if (control.dataset.multiple == "false") {
        let images = control.parentNode.parentNode.getElementsByClassName("uplloadImage");

        if (images.length > 0) {
            Animation.Notify(Language.GetCode("Base.RemoveImageBeforeAddNew"));
        } else {
            fileUpload.click();
        }
    } else {
        fileUpload.click();
    }
};

upload.fileChanged = function (e)
{
    var btnSendUpload = document.getElementById("btnSendUpload-" + upload.id);
    //  btnSendUpload.style.display = "block";

    upload.doUpload();
};
upload.remove = function (control)
{
    var container = control.parentNode;
    container.parentNode.removeChild(container);
};

upload.doUpload = function ()
{
    //Get The form
    var fileUpload = document.getElementById("fileUpload-" + upload.id);

    if (fileUpload.value != '')
    {
        var inputs = fileUpload.parentNode.getElementsByTagName("input");

        for (var i = 0; i < inputs.length; i++)
        {
            if (inputs[i].id == "hdApp")
            {
                var hdApp = inputs[i];
            }

            if (inputs[i].id == "hdIdElement")
            {
                var hdIdElement = inputs[i];
            }

            if (inputs[i].id == "hdIdSourceElement")
            {
                var hdIdSourceElement = inputs[i];
            }

            if (inputs[i].id == "hdCallBack")
            {
                var hdCallBack = inputs[i];
            }

            if (inputs[i].id == "hdAction")
            {
                var hdAction = inputs[i];
            }

            if (inputs[i].id == "hdIdUpload")
            {
                var hdIdUpload = inputs[i];
            }
            if (inputs[i].id == "uploadLoading")
            {
                var uploadLoading = inputs[i];
            }
        }

        if (uploadLoading != undefined)
        {
            uploadLoading.style.display = 'block';
        }

        var conteneur = fileUpload.parentNode;
        var token = hdIdElement.value + Date.now();
        var frUpload = document.getElementById("frUpload-" + upload.id);

        hdIdElement.value = token;

        var formUpload = frUpload.contentWindow.document.getElementById('formUpload');

        fileUpload.name = "fileUpload";

        //Add to the Form
        formUpload.appendChild(fileUpload);
        formUpload.appendChild(hdApp);
        formUpload.appendChild(hdIdElement);
        formUpload.appendChild(hdCallBack);
        formUpload.appendChild(hdAction);
        formUpload.appendChild(hdIdUpload);

        if (hdIdSourceElement != undefined) {
            formUpload.appendChild(hdIdSourceElement);
        }

        formUpload.submit();

        //On Remet les controle pour un autre envoir
        var dvUpload = document.getElementById("dvUpload-" + upload.id);
        fileUpload.value = "";
        fileUpload.name = "fileUpload-" + upload.id;
        ;
        dvUpload.appendChild(fileUpload);
        dvUpload.appendChild(hdApp);
        dvUpload.appendChild(hdIdElement);
        dvUpload.appendChild(hdCallBack);
        dvUpload.appendChild(hdAction);
        dvUpload.appendChild(hdIdUpload);

        if (hdIdSourceElement != undefined) {
            dvUpload.appendChild(hdIdSourceElement);
        }

        //Suppression de l'image par défaut
        dvUpload.parentNode.style.backgroundImage = "";

        var uploadImages = document.getElementById("uploadImages-" + upload.id);
        uploadImages.innerHTML += "<div class='loading' ><img src='" + document.location.origin + "/images/loading/load.gif' /></div>";

        var verify = upload.verifyFrame();
        var maxLength = 0;

        //On ajoute un interval de max 10 seconde pour envoyer l'image  
        upload.intervale = setInterval(function () {

            maxLength += 1;

            var verify = upload.verifyFrame();

            if (verify.indexOf("OK") > -1 || verify.indexOf("DOCUMENT") > -1 || verify.indexOf("ERROR") > -1)
            {

                if (uploadLoading != undefined)
                {
                    uploadLoading.style.display = 'none';
                }
                //On affiche l'image télécharger
                var location = document.location.href.split("/");

                var loading = uploadImages.getElementsByClassName("loading");

                //   uploadImages.removeChild(loading[0]);

                var verify = upload.verify();

                if (verify === true)
                {
                    uploadImages.innerHTML += "<div style='padding: 0 0px 10px 0;' class='uplloadImage' ><img style='width:100px; margin-right: 10px;'  src='" + document.location.origin + "/Data/Tmp/" + hdIdElement.value + ".jpg' /><i onclick='upload.remove(this)' class='fa fa-remove' style='color: red;'>&nbsp;</i></div> ";
                    if (loading != null) {
                        uploadImages.removeChild(loading[0]);
                    }
                } 
                else if (verify == "DOCUMENT")
                {
                    uploadImages.innerHTML += "<div style='padding: 0 0px 10px 0;' class='success uplloadImage' ><input type='hidden' value='"+ upload.resultDocument +"' />&nbsp;" + verify + "<i onclick='upload.remove(this)' class='fa fa-remove' style='color: red;'>&nbsp;</i>";
                    uploadImages.innerHTML +=  "</div> ";
                    
                    var loading = uploadImages.getElementsByClassName("loading");

                    if (loading != null) {
                        uploadImages.removeChild(loading[0]);
                    }
                } else
                {
                    uploadImages.innerHTML += "<div style='padding: 0 0px 10px 0;' class='error' >&nbsp;Impossible de telecharger ce document<i onclick='upload.remove(this)' class='fa fa-remove' style='color: red;'>&nbsp;</i></div> ";
                }

                upload.clearFrame();
                clearInterval(upload.intervale);
                window.setTimeout(hdCallBack.value, 100);
            }

            if (maxLength == 30) {


                clearInterval(upload.intervale);

                window.setTimeout(hdCallBack.value, 100);
                uploadImages.innerHTML += "<div style='padding: 0 0px 10px 0;' class='error' >&nbsp;Impossible de telecharger ce document<i onclick='upload.remove(this)' class='fa fa-remove' style='color: red;'>&nbsp;</i></div> ";

                var loading = uploadImages.getElementsByClassName("loading");

                if (loading != null) {
                    uploadImages.removeChild(loading[0]);
                }

            }

        }, 1000);
    }
};

/**
 * ON verifie L'iframe
 **/
upload.verifyFrame = function ()
{
    var frUpload = document.getElementById("frUpload-" + upload.id);
    var content = frUpload.contentDocument || frUpload.contentWindows.document;

    return content.body.innerHTML;
};

/*
 * 
 */
upload.clearFrame = function ()
{
    var frUpload = document.getElementById("frUpload-" + upload.id);
    var content = frUpload.contentDocument || frUpload.contentWindows.document;

    content.body.innerHTML = content.body.innerHTML.replace("OK", "").replace("DOCUMENT", "").replace("ERROR", "");
};

upload.verify = function ()
{
    var frUpload = document.getElementById("frUpload-" + upload.id);
    var content = frUpload.contentDocument || frUpload.contentWindows.document;

    if (content.body.innerHTML.indexOf("DOCUMENT") > -1)
    {
        //Extrace the data
        upload.extractResult(content.body.innerHTML);

        return "DOCUMENT";
    }

    return (content.body.innerHTML.indexOf("ERROR") == -1);
};

/***
 * Extrait le contenu
 * @param {type} content
 * @returns {undefined}
 */
upload.extractResult = function (content) {
    const regex = /(\{.*\})/;
    const match = content.match(regex);

    if (match) {
        const jsonString = match[1];

        try {
            // Conversion de la chaîne en objet JavaScript
            const jsonObject = JSON.parse(jsonString);

            // Accès aux valeurs de "type" et "file"
            const type = jsonObject.data["type:"];
            const file = jsonObject.data.file;

            upload.resultType = type;
            upload.resultDocument = file;
        } 
        catch (error) {
        }
    } 
};


upload.startResize = function (control) {
    console.log("startResize");
    isDragging = false;



    Event.AddById("moveImgDiv", "mousedown", function (event) {
        startDragImg(event);
    }
    );



    Event.AddById("moveImgDiv", "mouseup", function (event) {
        stopDragImg(event);
    }
    );

    Event.AddById("moveImgDiv", "mousemove", function (event) {

        if (isDragging) {
            moveDragImg(event);
        }
    });

    Event.AddById("moveImgDiv", "mouseout", function (event) {
        stopDragImg();
    });

};


function startDragImg(event) {

    let moveImgDiv = document.getElementById("moveImgDiv");
    moveImgDiv.style.cursor = "move";
    isDragging = true;

//	startX = event.offsetX;
//	startY = event.offsetY;
    startX = event.screenX;
    startY = event.screenY;

    //$("#moveImgDiv").css({"cursor": "move"});
}
;

function stopDragImg(event) {
    isDragging = false;
    startX = -1;
    startY = -1;

    let moveImgDiv = document.getElementById("moveImgDiv");

    moveImgDiv.style.cursor = "";
}
;

function moveDragImg(event) {

    if (startX != -1) {
//		var deltaX = event.offsetX - startX;
//		var deltaY = event.offsetY - startY;
        var deltaX = event.screenX - startX;
        var deltaY = event.screenY - startY;

        var logoImg = document.getElementById("logoImg");

        var imageTop = logoImg.style.top.replace("px", "");
        var Imageleft = logoImg.style.left.replace("px", "");

        imageTop -= -deltaY;
        Imageleft -= -deltaX;

        logoImg.style.top = imageTop + "px";
        logoImg.style.left = Imageleft + "px";
    }

    startDragImg(event);
}
;

upload.resize = function (control) {

    if (upload.resizeImage != undefined && upload.resizeImage != null) {

        console.log("resize ICICICI");
        upload.resizeImage.style.display = "none";
    }
};

upload.stopResize = function (control) {
    console.log("stopResize");
    upload.resizeImage = null;
};
