<!DOCTYPE html>
<html lang="de-ch" data-theme="light">
    <head>
        <%- include("../snippets/head.ejs", {
            title: title,
            date: date,
            desc: desc,
            url: url,
            env: env,
            sitetype: sitetype
        }) %>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="/css/blog.css">
    </head>
    <body>
        <%- include("../snippets/header.ejs") %>
        <%- include("../snippets/nav.ejs") %>
        <main>
            <h1>Blog Builder</h1>
            <p class="basic-text">
                Herzlich Willkommen zum Blog Builder. Benutze das Menu unten, um zu beginnen. 
                Wähle dazu einfach das gewünschte Element aus und leg los. Wenn du einen Link erstellen möchtest, 
                benutze diese Vorlage: &lt;a href="<i>#Dein Link#</i>"&gt;<i>#Dein anzuzeigender Text#</i>&lt;/a&gt;. Viel Erfolg!
            </p>
            <div class="blog_line"></div>
            <h1>Erstmal ein paar allgemeine Daten:</h1>
            <input type="text" id="basic_title" placeholder="Titel für den Blogpost" class="basic-input">
            <input type="text" id="basic_preview" placeholder="Kurze Zusammenfassung" class="basic-input">
            <!-- This is not needed anymore since blogs can be merged and therefore grouping different blogs in the database is not needed -->
            <input style="display: none;" type="text" id="basic_comment" placeholder="Privater Kommentar (Nur für Verwalter sichtbar, optional)" class="basic-input"> 
            <input type="text" id="basic_author" placeholder="Autor" class="basic-input">
            <label for="basic_img" class="basic-label">Titelbild aussuchen</label>
            <label for="basic_img" id="picture_overlay" style="height: 35vh; width: 60%; margin: 6vh 20%;">
                <div class="custom-file-upload" style="max-height: 35vh; box-sizing: border-box; max-width: 60vw;">
                    <div class="icon">
                        <img alt="Eine Datei" src="/img/svg/file.svg" id="hero_file_preview" style="height: 15vh;">
                    </div>
                    <div class="text">
                    <span>Klicken um ein neues Bild hochzuladen</span>
                    </div>
                </div>
            </label>
            <input style="display: none;" type="file" id="basic_img" accept="image/png, image/jpg, image/gif, image/jpeg, image/tiff, image/raw, image/bpm, image/webp, image/ico">
            <input type="text" id="basic_alt" placeholder="Beschreibe das Titelbild kurz (3-5 Wörter)" class="basic-input">
            <script>
                $("#basic_img").on("change", async (e) => {
                    data = await toBase64(e.target.files[0]);
                    $("#hero_file_preview").attr("src", data);
                });
            </script>
            <div class="blog_line"></div>
            <h1>Deine Auswahl</h1>
            <div id="baustelle"></div>
            <div class="blog_line"></div>
            <h1>Das ist die Vorschau:</h1>
            <div class="blog_line"></div>
            <div id="preview"></div>
            <div id="auswahl">
                <button type="button" id="add_title">Titel hinzufügen</button>
                <button type="button" id="add_subtitle">Untertitel hinzufügen</button>
                <button type="button" id="add_text">Paragraf hinzufügen</button>
                <button type="button" id="add_half_rechts" onclick="addHalf('rechts')">Halb Bild, Halb Text (Bild Rechts)</button>
                <button type="button" id="add_half_links" onclick="addHalf('links')">Halb Bild, Halb Text (Bild Links)</button>
                <button type="button" id="add_img">Einzelnes Bild hinzufügen</button>
                <button type="button" id="add_imgs">Mehrere Bilder hinzufügen</button>
                <button type="button" id="add_line">Trennlinie hinzufügen</button>
                <button type="button" id="done">Abschliessen</button>
            </div>
            <script>
                $("#add_title").click(addTitle);
                $("#add_subtitle").click(addSubtitle);
                $("#add_text").click(addText);
                $("#add_img").click(addImg);
                $("#add_imgs").click(addMultipleImg);
                $("#add_line").click(addLine);
                $("#done").click(done);


                const bau = $("#baustelle"),
                    pre = $("#preview"),
                    ids = [],
                    img_arr = [],
                    alt_arr = [],
                    img_suffix_arr = [],
                    img_names = [],
                    ruler_img = [];


                function addTitle () {
                    let input = document.createElement("input");
                    input.setAttribute("type", "text");
                    input.classList.add("basic-input");
                    input.placeholder = "Titel";
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let preview = document.createElement("h1");
                    input.addEventListener("input", () => {
                        preview.innerText = input.value;
                    });
                    preview.classList.add("blog_title");
                    preview.id = id + "_2";
                    pre.append(preview);
                };

                function addHalf (side_of_img) {
                    let div = document.createElement("div");
                    div.classList.add("blog_half");
                    let img = document.createElement("img");
                    let id1 = randomId();
                    ids.push(id1);
                    img.id = id1;
                    let p = document.createElement("p");
                    let id2 = randomId();
                    ids.push(id2);
                    p.id = id2;
                    let input1 = document.createElement("input");
                    let input2 = document.createElement("input");
                    let input3 = document.createElement("input");
                    input1.classList.add("basic-input");
                    input2.classList.add("basic-input");
                    input3.classList.add("basic-input");
                    let id3 = randomId();
                    let id4 = randomId();
                    let id5 = randomId();
                    ids.push(id3);
                    ids.push(id4);
                    ids.push(id5);
                    input1.id = id3;
                    input2.id = id4;
                    input3.id = id5;
                    input1.setAttribute("type", "text");
                    input1.placeholder = "Paragraf";
                    input2.setAttribute("type", "file");
                    input2.accept = "image/png, image/jpg, image/gif, image/jpeg, image/tiff, image/raw, image/bpm, image/webp, image/ico";
                    input2.placeholder = "Bild";
                    input3.setAttribute("type", "text");
                    input3.placeholder = "Kurze Beschriebung des Bildes (ca. 3-5 Wörter)";
                    input1.addEventListener("input", () => {
                        p.innerText = input1.value;
                    });
                    input3.addEventListener("input", () => {
                        img.alt = input3.value;
                    });
                    input2.addEventListener("change", async (e) => {
                        let file = e.target.files[0];
                        if (file) {
                            img.src = await toBase64(file);
                        } else {
                            img.src = "";
                        };
                    });
                    bau.append(input1);
                    bau.append(input2);
                    bau.append(input3);
                    if (side_of_img === "rechts") {
                        $(div).append(p);
                        $(div).append(img);
                    } else {
                        $(div).append(img);
                        $(div).append(p);
                    };
                    pre.append(div);
                };

                function addSubtitle () {
                    let input = document.createElement("input");
                    input.setAttribute("type", "text");
                    input.placeholder = "Untertitel";
                    input.classList.add("basic-input");
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let preview = document.createElement("h2");
                    input.addEventListener("input", () => {
                        preview.innerText = input.value;
                    });
                    preview.classList.add("blog_subtitle");
                    preview.id = id + "_2";
                    pre.append(preview);
                };

                function addText () {
                    let input = document.createElement("textarea");
                    input.innerText = "Paragraf";
                    input.classList.add("basic-input");
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let preview = document.createElement("p");
                    input.addEventListener("keydown", () => {
                        preview.innerText = input.value;
                    });
                    preview.classList.add("blog_text");
                    preview.id = id + "_2";
                    pre.append(preview);
                };

                function addImg () {
                    let input = document.createElement("input");
                    input.setAttribute("type", "file");
                    input.classList.add("basic-input");
                    input.accept = "image/png, image/jpg, image/gif, image/jpeg, image/tiff, image/raw, image/bpm, image/webp, image/ico";
                    input.placeholder = "Bild";
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let preview = document.createElement("img");
                    preview.id = id + "_2";
                    preview.classList.add("blog_img");
                    input.addEventListener("change", (e) => {
                        const file = e.target.files[0];
                        if (file) {
                            const reader = new FileReader();
                            reader.onload = function(event) {
                                preview.src = event.target.result;
                            };
                            reader.readAsDataURL(file);
                        } else {
                            preview.src = '';
                        };
                    });
                    pre.append(preview);
                    let alt = document.createElement("input");
                    alt.setAttribute("type", "text");
                    alt.classList.add("basic-input");
                    alt.placeholder = "Kurze Beschriebung des Bildes (ca. 3-5 Wörter)";
                    alt.id = id + "_3";
                    bau.append(alt);
                    alt.addEventListener("input", () => {
                        preview.alt = alt.value;
                    });
                };

                function addMultipleImg () {
                    let input = document.createElement("input");
                    input.classList.add("basic-input");
                    input.setAttribute("multiple", "true");
                    input.accept = "image/png, image/jpg, image/gif, image/jpeg, image/tiff, image/raw, image/bpm, image/webp, image/ico";
                    input.setAttribute("type", "file");
                    input.placeholder = "Bild";
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let preview = document.createElement("div");
                    let id2 = randomId();
                    ids.push(id2);
                    preview.id = id2;
                    input.addEventListener("change", async (e) => {
                        const files = e.target.files;
                        let arr = [];
                        if (files.length > 0) {
                            for (let i = 0; i < files.length; i++) {
                                let res = await toBase64(files[i]);
                                arr.push(res);
                            };
                            carousel = await createCarouselHTML(arr);
                            preview.innerHTML = carousel[0];
                            eval(carousel[1].replace('elm.src += "?tr=w-100,h-100"', "console.log('REPLACEME')"));
                        } else {
                            preview.innerHTML = "Fehler";
                        };
                    });
                    pre.append(preview);
                };

                function toBase64 (file) {
                    return new Promise((resolve, reject) => {
                        const reader = new FileReader();
                        reader.onload = () => resolve(reader.result);
                        reader.onerror = reject;
                        reader.readAsDataURL(file);
                    });
                };

                function addLine () {
                    let input = document.createElement("div");
                    input.classList.add("blog_line");
                    let id = randomId();
                    ids.push(id);
                    input.id = id;
                    bau.append(input);
                    let input2 = document.createElement("div");
                    input2.classList.add("blog_line");
                    input2.id = id;
                    pre.append(input2);
                };

                function done () {
                    let content = document.getElementById("preview");
                    let pics = content.querySelectorAll("img");
                    let para = content.querySelectorAll("p");
                    pics.forEach(elm => {
                        elm.classList.remove("active");
                        img_arr.push(elm.src);
                        alt_arr.push(elm.alt);
                        img_suffix_arr.push(elm.id);
                        let name = elm.alt;
                        elm.src = "https://ik.imagekit.io/zmt/blog/" + name.replaceAll(" ", "-") + "___" + elm.id;
                        if (elm.id in ruler_img) elm.src += "?tr=w-200,h-200";
                        img_names.push(elm.src);
                    });
                    para.forEach(elm => {
                        let text = elm.innerText;
                        text = text.replaceAll("&gt;", ">").replaceAll("&lt;", "<");
                        elm.innerHTML = text;
                    });
                    fetch(window.location.origin + "/post/upload/imagekit", {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        mode: "cors",
                        cache: "default",
                        body: JSON.stringify({
                            img: img_arr,
                            alt: alt_arr,
                            suffix: img_suffix_arr
                        })
                    });
                    createBlogPost(content.innerHTML);
                };

                function randomId () {
                    let result = 'auto_';
                    const char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                    for (let i = 0; i < 27; i++) {
                        result += char.charAt(Math.floor(Math.random() * char.length));
                    };
                    return result;
                };

                async function createBlogPost (content) {
                    const t = $("#basic_title"),
                        p = $("#basic_preview"),
                        c = $("#basic_comment"),
                        a = $("#basic_author");
                    if (
                        content === "" || content === undefined || content === null ||
                        t.val() === "" || t.val() === undefined || t.val() === null ||
                        p.val() === "" || p.val() === undefined || p.val() === null ||
                        a.val() === "" || a.val() === undefined || a.val() === null
                    ) {
                        console.error("Something is empty...");
                        return;
                    };
                    if (c.val() === "" || c.val() === undefined || c.val() === null) c.val("Kein Kommentar");
                    let data = {
                        img: {},
                        alt: {}
                    };
                    let file = document.getElementById("basic_img").files[0];
                    let hero = await toBase64(file);
                    let heroid = await randomId();
                    let heroname = $("#basic_alt").val();
                    fetch(window.location.origin + "/post/upload/imagekit", {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        mode: "cors",
                        cache: "default",
                        body: JSON.stringify({
                            img: [hero],
                            alt: [heroname],
                            suffix: [heroid]
                        })
                    });
                    await img_names.unshift("https://ik.imagekit.io/zmt/blog/" + heroname.replaceAll(" ", "-") + "___" + heroid);
                    await alt_arr.unshift(heroname);
                    fetch(window.location.origin + "/post/blog", {
                        method: "POST",
                        headers: {"Content-Type": "application/json"},
                        mode: "cors",
                        cache: "default",
                        body: JSON.stringify({
                            title: t.val(),
                            preview: p.val(),
                            author: a.val(),
                            comment: c.val(),
                            content: content,
                            img: {
                                img: img_names,
                                alt: alt_arr
                            }
                        })
                    });
                };

                function createCarouselHTML (img_arr) {
                    let ids = [];
                    let container = document.createElement("div");
                    container.classList.add("blog_carousel");
                    ids.push(randomId());
                    container.classList.add(ids[0]);
                    let main = document.createElement("div");
                    main.classList.add("blog_c-main");
                    ids.push(randomId());
                    main.classList.add(ids[1]);
                    main = $(main);
                    container = $(container);
                    let b1 = document.createElement("button");
                    let b2 = document.createElement("button");
                    b1.classList.add("blog_carousel_next");
                    b2.classList.add("blog_carousel_prev");
                    let b1id = "blog_carousel_next_" + randomId();
                    let b2id = "blog_carousel_prev_" + randomId();
                    ids.push(b1id);
                    ids.push(b2id);
                    b1.id = b1id;
                    b2.id = b2id;
                    b1.setAttribute("type", "button");
                    b2.setAttribute("type", "button");
                    let ruler = document.createElement("div");
                    ruler.classList.add("blog_c-ruler");
                    ids.push(randomId());
                    ruler.classList.add(ids[4]);
                    ids.push(randomId());
                    ids.push(randomId());
                    ids.push(randomId());
                    ids.push(randomId());
                    ids.push(randomId());
                    img_arr.forEach(elm => {
                        let img = document.createElement("img");
                        ids.push(randomId());
                        img.classList.add(ids[ids.length - 1]);
                        img.id = ids[ids.length - 1];
                        ruler_img.push(img.id);
                        img.src = elm;
                        img.alt = "Keine Beschreibung für dieses Bild...";
                        main.append(img);
                    });
                    container.append(main);
                    container.append(b1);
                    container.append(b2);
                    container.append(ruler);
                    let script = document.createElement("script");
                    let scriptHTML = `getQuery(".blog_c-ruler.${ids[4]}").get(0).html(getQuery(".blog_c-main.${ids[1]}").get(0).html());\n\n`;
                    scriptHTML += `const arr_${ids[5]} = [\n`;
                    img_arr.forEach((elm, i) => {
                        scriptHTML += `    getQuery(".${ids[i + 10]}"),\n`;
                    });
                    scriptHTML += `];\n\ngetQuery(".blog_c-ruler.${ids[4]}").get(0).getQuery("img").forEach(elm => elm.src += "?tr=w-100,h-100");`
                    scriptHTML += `\n\nlet current_${ids[6]} = 1;\n\narr_${ids[5]}[current_${ids[6]} - 1].toggleClass("active");\n\n`;
                    scriptHTML += `function next_${ids[7]} () {\n    current_${ids[6]} + 1 > arr_${ids[5]}.length ?\n    current_${ids[6]} = 1 :\n    current_${ids[6]}++;\n    `;
                    scriptHTML += `current_${ids[6]} === 1 ?\n    arr_${ids[5]}[arr_${ids[5]}.length - 1].toggleClass("active") :\n    `;
                    scriptHTML += `arr_${ids[5]}[current_${ids[6]} - 2].toggleClass("active");\n    arr_${ids[5]}[current_${ids[6]} - 1].toggleClass("active");\n};\n`;
                    scriptHTML += `function prev_${ids[8]} () {\n    current_${ids[6]} - 1 === 0 ?\n    current_${ids[6]} = arr_${ids[5]}.length :\n    `
                    scriptHTML += `current_${ids[6]}--;\n    current_${ids[6]} === arr_${ids[5]}.length ?\n    arr_${ids[5]}[0].toggleClass("active") :\n    arr_${ids[5]}[current_${ids[6]}].toggleClass("active");\n    `
                    scriptHTML += `arr_${ids[5]}[current_${ids[6]} - 1].toggleClass("active");\n};\nfunction to_${ids[9]} (i) {\n    arr_${ids[5]}[current_${ids[6]} - 1].toggleClass("active");\n    `
                    scriptHTML += `arr_${ids[5]}[i - 1].toggleClass("active");\n    current_${ids[6]} = i;\n};\n\ngetElm("${b1id}").click(next_${ids[7]});\n`
                    scriptHTML += `getElm("${b2id}").click(prev_${ids[8]});\n\narr_${ids[5]}.forEach((elm, i) => {\n    elm.get(1).click(() => to_${ids[9]} (i + 1));\n});`;
                    script.innerHTML = scriptHTML;
                    container.append(script);
                    let dummy = document.createElement("div");
                    dummy = $(dummy);
                    dummy.append(container);
                    return [dummy.html(), scriptHTML];
                };
            </script>
        </main>
        <div style="height: 120px;"></div>
    </body>
</html>