/* 
 * Quilljs Heinzelmann
 * Toolsbar: Usser.php -> getQuillToolbar();
 */



if (typeof Block !== "function") {


    var outlookImg = null;
    console.log("Quilljs laden...");
    let Block = Quill.import('blots/block');

    let Container = Quill.import('blots/container');




    var Image = Quill.import('formats/image');
    Image.className = 'hm-img-fluid';
    Image.sanitize = function (url) {
        return url; // You can modify the URL here
    };
    Quill.register(Image, true);
// Add fonts to whitelist
    const Delta = Quill.import('delta');

    var quill = new Quill('#editor', {
        theme: 'snow',
        modules: {
            toolbar: '#toolbar-container',
            clipboard: {
                matchVisual: false
            }

        }
    });

    let savedRange = null;

        quill.on("selection-change", (range) => {
        // range is null when editor blurs
        if (range) savedRange = range;
        })

        const sizePicker = document.querySelector(".ql-size");
        sizePicker?.addEventListener("mousedown", (e) => {
            e.preventDefault();
        });


        const sizeSelect = document.querySelector("#FontSizeSelect");
            
            // keep editor selection when clicking the UI
            sizeSelect.addEventListener("mousedown", (e) => {
            e.preventDefault(); // stops blur => keeps selection
            });
            $(".ql-picker-item").on('click', function(event){
                 e.preventDefault();
            });




    console.log("Quill:", quill);
    quill.clipboard.addMatcher(Node.TEXT_NODE, function (node, delta) {
        var regex = /((http|https|ftp|ftps)\:\/\/(\S*)?)/g;
        if (typeof (node.data) !== 'string')
            return;
        var matches = node.data.match(regex);

        if (matches && matches.length > 0) {
            var ops = [];
            var str = node.data;
            matches.forEach(function (match) {
                console.log("Link matched!");
                var split = str.split(match);
                var beforeLink = split.shift();
                ops.push({insert: beforeLink});
                ops.push({insert: match, attributes: {link: match}});
                str = split.join(match);
            });
            ops.push({insert: str});
            delta.ops = ops;
        }

        return delta;
    });

    quill.clipboard.addMatcher('img', (node, delta) => {
        console.log("Img");
        console.log(node);
        var image = node.src;
        var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
        var blob = base64ToBlob(base64ImageContent, 'image/png');

        console.log(blob);
        if (blob === null) {
            if (!node.src.includes("file:")) {
                return new Delta().insert({image: node.src});
            } else {
                console.log(outlookImg);
                let formData = new FormData();

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

                // 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) {
                        if(data !== "Nofile"){
                        //         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
                });
            }
        } else {
            console.log("Bild über Copy-Paste hinzufügen.");
            // generate a form data
            let formData = new FormData();

            // append blob data
            formData.append('file', blob);
            var kb = 0;
            if(typeof moduleVar !== "undefined"){
                if (moduleVar==="knowledgebase") {
                    kb = 1;
                }
            }
            // or just append the file

            // upload image to your server
            $.ajax({
                url: 'index.php?module=upload&event=uploadImageDirectly&kb='+kb,
                type: 'POST',
                data: formData,
                success: function (data) {
                    if(data !== "Nofile"){
                    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%');
                    setTimeout(() => quill.setSelection(quill.getSelection().index + 1, 0), 0);
                    // 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();


    });






    quill.on('text-change', function () {
        $("#LongDescr").val(quill.root.innerHTML);
        if (typeof newTicket !== "undefined" && typeof saveAsDraft !== "undefined")
        {
            if (newTicket === 1 && saveAsDraft === 1) {
                submitTemp('LongDescr');
            }
        }

    });

    quill.on('text-change', function (delta, oldDelta, source) {
        var regex = /https?:\/\/[^\s]+$/;
        if (delta.ops.length === 2 && delta.ops[0].retain && isWhitespace(delta.ops[1].insert)) {
            var endRetain = delta.ops[0].retain;
            var text = quill.getText().substr(0, endRetain);
            var match = text.match(regex);

            if (match !== null) {
                var url = match[0];

                var ops = [];
                if (endRetain > url.length) {
                    ops.push({retain: endRetain - url.length});
                }

                ops = ops.concat([
                    {delete: url.length},
                    {insert: url, attributes: {link: url}}
                ]);

                quill.updateContents({
                    ops: ops
                });
            }
        }
    });

    function isWhitespace(ch) {
        var whiteSpace = false
        if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
            whiteSpace = true;
        }
        return whiteSpace;
    }

    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;
        }


    }

    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);
        var kb = 0;
        console.log("Module: "+moduleVar);
        if(typeof moduleVar !== "undefined"){
            if (moduleVar==="knowledgebase") {
                kb = 1;
            }
        }
        // upload image to your server
        $.ajax({
            url: 'index.php?module=upload&event=uploadImageDirectly&kb='+kb,
            type: 'POST',
            data: formData,
            success: function (data) {
                if(data !== "Nofile"){
                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.');
            }
        };
    }

    quill.keyboard.bindings[9].unshift({
        key: 9,
        handler: function (range) {
            //insertTab();
            $("#IndentMinus1").click();
            return false;
        }
    });

    /**
     * insertSnippet
     */
    function insertSnippet(id) {
        $.get("index.php?module=ticket&class=snippets&event=getSnippetContent&id=" + id, function (data) {
            console.log(data);
            let index = (quill.getSelection() || {}).index;
            if (index === undefined || index < 0) {
                index = quill.getLength();
            }

          //  quill.insertText(index, data);
            quill.clipboard.dangerouslyPasteHTML(index, data);
            $("#myBigIFrameModal").modal('hide');
            $(".fancybox-close")[0].click();
        });

    }

    function insertTab() {

        let index = (quill.getSelection() || {}).index;
        if (index === undefined || index < 0) {
            index = quill.getLength();
        }
        quill.insertText(index, '    ');
    }


    /**
     * editHTML
     */
    function editHTML() {
        var color = $('#editHTMLBtn').css('color');
        console.log(color);
        if (color == 'rgb(0, 0, 255)') {
            $("#editor").show();
            var editor = document.getElementsByClassName('ql-editor');
            editor[0].innerHTML = $("#LongDescr").val();
            $("#LongDescr").css({"visibility": "hidden", "height": "0px"});
            $('#editHTMLBtn').css({"color": "#333333"});

        } else {

            $("#editor").hide();
            $("#LongDescr").css({"visibility": "visible", "height": "200px"});
            $('#editHTMLBtn').css({"color": "#0000ff"});


        }


    }


    function insertTableQuill() {
        console.log("Inserting Table");
        const table = quill.getModule('table');
        table.insertTable(2, 2);

//    let range = quill.getSelection(true);
////    quill.insertText(range.index, '\n', Quill.sources.USER);
////    quill.insertEmbed(range.index + 1, 'Table', true, Quill.sources.USER);
////    quill.setSelection(range.index + 2, Quill.sources.SILENT);
//    var html = quill.root.innerHTML;
//    let index = (quill.getSelection() || {}).index;
//    if (index === undefined || index < 0) {
//        index = quill.getLength();
//    }
//    quill.root.innerHTML = '<table><tbody><tr><td>ABC</td><td>DEF</td></tr><tr><td>GHI</td><td>JKL</td></tr></tbody></table>';
//
//    console.log("Index is " + index);
        // console.log(html.substring(0, index));

        //console.log(html.substring(index));
        //var output = html.substring(0, index) + '<table><tbody><tr><td>ABC</td><td>DEF</td></tr><tr><td>GHI</td><td>JKL</td></tr></tbody></table>' + html.substring(index);

        //  quill.root.innerHTML = output;
        //  quill.clipboard.dangerouslyPasteHTML(0, '<table><tbody><tr><td>ABC</td><td>DEF</td></tr><tr><td>GHI</td><td>JKL</td></tr></tbody></table>');
    }

    function checkTabPress(e) {

        "use strict";
        // pick passed event or global event object if passed one is empty
        e = e || event;
        if (e.keyCode == 9 && $("#ShortDescr").is(":focus")) {
            quill.focus();
             e.preventDefault();;
        }
    }

    var body = document.querySelector('body');
    $(window).keydown(function (e) {
        checkTabPress(e);
    });
  //  body.addEventListener('keypress ', checkTabPress);

    $("#editor").bind("paste", function (e) {
// access the clipboard using the api
        var items = e.originalEvent.clipboardData.items;
        for (let i = 0; i < items.length; i++) {


            if (items[i].type.indexOf('image') === 0) {
                items[i].getAsFileSystemHandle(function (s) {
                    console.log(console.log("Image in item: " + s));

                })

                image = items[i].getAsFile();
                outlookImg = image;
                console.log("Image file in item: ", image);
            }
        }
    });
}