/* 
 * Quilljs Heinzelmann
 * Toolsbar: Usser.php -> getQuillToolbar();
 */
console.log("Quilljs laden...");
var Image = Quill.import('formats/image');
Image.className = 'hm-img-fluid';
Quill.register(Image, true);

const Delta = Quill.import('delta');

var Parchment = Quill.import("parchment");

let CustomClass = new Parchment.Attributor.Class('custom', 'ql-custom', {
    scope: Parchment.Scope.INLINE
});

Quill.register(CustomClass, true);

$(".wf_textarea").each(function () {
    var txtID = ($(this).attr('id'));
    var fieldID = txtID.split('_')[1];
    console.log("textarea_" + fieldID);
    console.log($("#textarea_" + fieldID).val());

    var quillID = 'quill_' + fieldID;
    var quill = new Quill('#' + quillID, {
        theme: 'snow',
        modules: {
            magicUrl: {
                // Regex used to check URLs during typing
                urlRegularExpression: /((http|https|ftp|ftps)\:\/\/(\S*)?)/g,
                // Regex used to check URLs on paste
                globalRegularExpression: /((http|https|ftp|ftps)\:\/\/(\S*)?)/g
            },
            toolbar: '#toolbar-container-' + fieldID

        }
    });

    quill.clipboard.addMatcher('img', (node, delta) => {
        console.log(node.src);
        const url = 'http://www.placehold.it/666x333.jpg';
        console.log("This is caLL?");
        var image = node.src;
        var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");

        var filename = 'my_cool_image.png'
        var blob = base64ToBlob(base64ImageContent, 'image/png');

        console.log(blob);
        if (blob === null) {
            return new Delta().insert({image: node.src});
        } else {
            // generate a form data
            let formData = new FormData();

            // append blob data
            formData.append('file', blob);

            // or just append the file

            // upload image to your server
            $.ajax({
                url: 'index.php?module=upload&event=uploadImageDirectly',
                type: 'POST',
                data: formData,
                success: function (data) {
                    console.log(data);
                    //         return new Delta().insert({image: 'index.php?module=upload&event=ShowImage&name=' + data});
                    let index = (quill.getSelection() || {}).index;
                    if (index === undefined || index < 0) {
                        index = quill.getLength();
                    }

                    quill.insertEmbed(index, 'image', 'index.php?module=upload&event=ShowImage&name=' + data, 'user');
                    quill.formatText(index, index + 1, 'max-width', '100%');
                    // return new Delta().insert({image: 'index.php?module=upload&event=ShowImage&name=' + data});

                },
                cache: false,
                contentType: false,
                processData: false
            });
            console.log(formData);
        }

        return new Delta();


    });
    const value = $("#textarea_" + fieldID).val();
    const delta = quill.clipboard.convert(value);

    quill.setContents(delta, 'silent')

    quill.on('text-change', function () {
        $("#textarea_" + fieldID).val(quill.root.innerHTML);
    });

});

function imageHandler(imageDataUrl, type, imageData) {

    var filename = 'my_cool_image.png'
    var blob = imageData.toBlob();
    var file = imageData.toFile(filename);
    console.log(file);

    // generate a form data
    let formData = new FormData();

    // append blob data
    formData.append('filename', filename);
    formData.append('fileBlob', blob);

    // or just append the file
    formData.append('file', file);

    // upload image to your server
    $.ajax({
        url: 'index.php?module=upload&event=uploadImageDirectly',
        type: 'POST',
        data: formData,
        success: function (data) {
            console.log(data);
            let index = (quill.getSelection() || {}).index;
            if (index === undefined || index < 0) {
                index = quill.getLength();
            }

            quill.insertEmbed(index, 'image', 'index.php?module=upload&event=ShowImage&name=' + data, 'user');
            quill.formatText(index, index + 1, 'max-width', '100%');
        },
        cache: false,
        contentType: false,
        processData: false
    });
    console.log(formData);
}
function selectLocalImage() {
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.click();
    // Listen upload local image and save to server
    input.onchange = () => {
        const file = input.files[0];
        // file type is only image.
        if (/^image\//.test(file.type)) {
            saveToServer(file);
        } else {
            console.warn('You could only upload images.');
        }
    };
}

function insertSnippet(id, fieldid) {
    console.log("Insert Snippet!" + fieldid);
    // Should be true

    $.get("index.php?module=ticket&class=snippets&event=getSnippetContent&id=" + id, function (data) {
        var container = document.querySelector("#quill_" + fieldid);
        var quill = Quill.find(container);
        let index = (quill.getSelection() || {}).index;
        if (index === undefined || index < 0) {
            index = quill.getLength();
        }

        quill.insertText(index, data);
        $("#myBigIFrameModal").modal('hide');
    });

}

function base64ToBlob(base64, mime)
{
    mime = mime || '';
    var sliceSize = 1024;
    try {
        var byteChars = window.atob(base64)
        var byteArrays = [];

        for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
            var slice = byteChars.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }
        return new Blob(byteArrays, {type: mime});


    } catch (e) {
        console.log("img but not base64");
        return null;
    }


}




