const getTranscriptText = (e, t) => {
    let o = [];
    sessionList.forEach((e => {
        o.unshift(e)
    }));
    let n = "<div>",
        i = {};
    n += "<div style='font-size:20pt; color: #2F5496'>Transcripts<br></div>", o.forEach(((s, a) => {
        if (s.text && s.text.length && (0 === a || s.startedAt !== o[a - 1].startedAt)) {
            let o = "",
                a = "You" === s.person ? appUser : s.person;
            if (s.highlight.length && e && (o = s.highlight[0], s.highlight[0])) {
                let e = s.highlight[0],
                    t = i[e] ? i[e] : [];
                t.push({
                    text: s.text,
                    time: getTimeStr(startTime, s.startedAt),
                    person: a
                }), i[e] = t
            }
            if (n += "<div style='font-size:11pt'>", n = n + "<i style='color:#9e9e9e'>" + a, t && (n += ` (${getTimeStr(startTime,s.startedAt)})`), n += ": </i>", e && o.length) {
                const e = bookmarkList.find((e => e.color === o)).code;
                n += `<div style="color:${e}; display:inline">`
            }
            n += s.text, e && o.length && (n += "</div>"), n += "<br><br></div>"
        }
    })), n += "</div>";
    let s = "";
    return e && (s += "<div>", s += "<div style='font-size:20pt; color: #2F5496'>Highlights<br></div>", Object.keys(i).forEach((e => {
        let t = bookmarkList.find((t => t.color === e)),
            o = t.name,
            n = t.code;
        s += "<div>", s += `<span style="color:${n}; font-weight:bold; font-size:14pt">${o}:<br></span>`, i[e].forEach((e => {
            s += `<div style='font-size:11pt'><i style='color:#9e9e9e'>${e.person} (${e.time}): </i>${e.text}<br><br></div>`
        })), s += "</div>"
    })), s += "</div>"), `<div style='font-family:calibri'><div style='font-size:14pt'>${startTime}<br></div>` + s + n + "</div>"
},
Export2Txt = (e, t = "") => {
    let o = document.createElement("a"),
        n = e.replaceAll("<br>", "\n"),
        i = document.createElement("div");
    i.style.display = "none", i.innerHTML = n;
    let s = i.innerText;
    const a = new File([s], "filename"),
        d = URL.createObjectURL(a);
    return o.href = d, o.download = `${t}.txt`, document.body.appendChild(o), o.click(), document.body.removeChild(o), Promise.resolve(1)
},
Export2Pdf = (e, t = "") => {
    const o = window.html2pdf;
    t = t ? t + ".pdf" : `${getDefaultName()}.pdf`;
    let n = document.createElement("div");
    n.innerHTML = e, document.body.appendChild(n);
    const i = {
        margin: [8, 16, 8, 16],
        filename: `${t}.pdf`,
        enableLinks: !1,
        pagebreak: {
            avoid: ["div"],
            mode: ["css"]
        },
        image: {
            type: "jpeg",
            quality: 1
        },
        html2canvas: {
            allowTaint: !0,
            dpi: 144,
            letterRendering: !0,
            logging: !1,
            scale: 2,
            scrollX: 0,
            scrollY: 0
        }
    };
    return new Promise(((e, t) => {
        o().from(n).set(i).toPdf().get("pdf").then((e => {
            const t = e.internal.getNumberOfPages();
            for (let o = 1; o < t + 1; o++) e.setPage(o), e.setFontSize(14), e.text(`${o}/${t}`, e.internal.pageSize.getWidth() - 10, e.internal.pageSize.getHeight() - 5);
            document.body.removeChild(n)
        })).save().then((() => {
            e("Downloaded")
        })).catch((e => t(e)))
    }))
},
Export2Word = (e, t = "") => {
    var o = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>" + e + "</body></html>",
        n = new Blob(["\ufeff", o], {
            type: "application/msword"
        }),
        i = "data:application/vnd.ms-word;charset=utf-8," + encodeURIComponent(o);
    t = t ? `${t}.doc` : `${getDefaultName()}.doc`;
    var s = document.createElement("a");
    return document.body.appendChild(s), navigator.msSaveOrOpenBlob ? navigator.msSaveOrOpenBlob(n, t) : (s.href = i, s.download = t, s.click()), document.body.removeChild(s), Promise.resolve(1)
},
disableSaveToLaxisCloud = e => {
    const t = document.getElementById("laxis-confirm-download");
    t && (t.disabled = e, t.style.color = t.disabled ? "#999" : "");
    const o = document.getElementById("extension");
    o && (o.onchange = () => {
        t && (t.disabled = e && "app" === o.value, t.style.color = t.disabled ? "#999" : "")
    });
    const n = document.getElementById("autoSaveCheck");
    n && (n.disabled = e)
},
displayGoogleMeetQuota = (e, t) => {
    const o = document.getElementById("google-meet-quota");
    o && -1 !== t && 0 !== t && (e < t ? (o.innerHTML = `Autosave to Laxis cloud: ${e.toFixed(0)} / ${t.toFixed(0)} minutes. <br/> Please <span style='color: #2196f3;'>upgrade</span> to enjoy unlimited autosave.`, disableSaveToLaxisCloud(!1)) : (o.innerHTML = `Autosave to Laxis cloud: <span style='color: #E94B4B;'>${e.toFixed(0)} / ${t.toFixed(0)}</span> minutes. <br/> Please <span style='color: #2196f3;'>upgrade</span> to enjoy unlimited autosave.`, disableSaveToLaxisCloud(!0)), o.style.display = "block")
},
reDisplayPrompt = () => {
    const e = document.getElementById("login-prompt");
    e && (e.style.display = "block"), chrome.storage.local.remove("token")
},
addRemindLogin = () => {
    console.log("add login");
    const e = document.getElementById("laxis-miniPanel"),
        t = document.getElementById("laxis-expandPanel"),
        o = document.createElement("div");
    o.title = "Login to autosave notes", o.id = "laxis-remindLogin", o.style.width = "40px", o.style.height = "40px", o.classList.add("miniButtonContainer"), o.style.border = "0", o.addEventListener("click", signup), o.style.padding = "0";
    const n = createRemindLoginIcon();
    n.id = "remindLoginIcon", o.appendChild(n), n.id = "remindLoginIcon", o.style.display = "none", e.insertBefore(o, t)
},
reDisplayRemindLogin = () => {
    console.log("redisplay");
    const e = document.getElementById("laxis-remindLogin");
    e && (e.style.display = "block"), chrome.storage.local.remove("token")
},
getTopics = (e, t) => window.fetch(`${domainUrl}/api/v2/templates/${e}/topics`, t),
Export2App = async (e, t = !1) => new Promise(((o, n) => {
    chrome.storage.local.get(["token"], (function(i) {
        if (i.token) {
            let s = document.getElementById("laxis-openDownloadMenu"),
                a = document.getElementById("laxis-download-menu-mini");
            s.classList.add("loading"), a.classList.add("loading"), window.fetch(`${domainUrl}/api/v2/templates?quick-note=true`, {
                method: "GET",
                headers: {
                    Authorization: `Bearer ${i.token}`,
                    "Content-Type": "application/json"
                }
            }).then((s => {
                200 === s.status ? s.json().then((s => {
                    s.items.length ? getTopics(s.items[0].id, {
                        method: "GET",
                        headers: {
                            Authorization: `Bearer ${i.token}`,
                            "Content-Type": "application/json"
                        }
                    }).then((a => {
                        a.json().then((a => {
                            const d = a.items;
                            let l = [];
                            if (getTranscript(currentTranscriptId).forEach((({
                                    image: t,
                                    person: o,
                                    text: n,
                                    startedAt: i,
                                    endedAt: s,
                                    highlight: a
                                }) => {
                                    let r = [];
                                    if (a && e) {
                                        const e = bookmarkList.find((e => e.color === a[0]));
                                        if (e) {
                                            const t = d.find((t => t.color.toLowerCase() === e.code.toLowerCase()));
                                            t && (r = [t.id])
                                        }
                                    }
                                    n && l.push({
                                        imageUrl: t,
                                        person: "You" === o ? appUser : o,
                                        startedAt: i,
                                        endedAt: s || i,
                                        highlights: r,
                                        text: n
                                    })
                                })), l.length) {
                                let e = JSON.stringify({
                                        meetingId: currentTranscriptId,
                                        meetingName: document.getElementById("meeting-name").innerText,
                                        templateId: s.items[0].id,
                                        transcripts: l,
                                        isEnded: t
                                    }),
                                    a = {
                                        Authorization: `Bearer ${i.token}`,
                                        "Content-Type": "application/json"
                                    },
                                    d = get(APPLICATION_SPEECH_IDS) || [],
                                    r = d.findIndex((e => e.ext === currentTranscriptId));
                                if (-1 === r) window.fetch(`${domainUrl}/api/v1/speeches/google-meet`, {
                                    method: "POST",
                                    headers: a,
                                    body: e
                                }).then((e => {
                                    200 === e.status ? e.json().then((e => {
                                        set(APPLICATION_SPEECH_IDS, [...d, {
                                            ext: currentTranscriptId,
                                            app: e.id
                                        }]), chrome.runtime.sendMessage({
                                            type: "transcriptId",
                                            transcriptId: e.id
                                        }), o(e.id)
                                    })) : 401 === e.status ? (e.json().then((e => {
                                        saveLog(`Export2App 401 fail 1 ${i.token} ${e.id} ${e.message}`)
                                    })), reDisplayPrompt(), n("Expired token")) : e.json().then((e => {
                                        n(e.message)
                                    }))
                                })).catch((e => {
                                    n(e)
                                }));
                                else {
                                    let t = d[r].app;
                                    window.fetch(`${domainUrl}/api/v1/speeches/google-meet/${t}`, {
                                        method: "PUT",
                                        headers: a,
                                        body: e
                                    }).then((e => {
                                        200 === e.status ? e.json().then((() => {
                                            o(t)
                                        })) : 401 === e.status ? (e.json().then((e => {
                                            saveLog(`Export2App 401 fail 2 ${i.token} ${t} ${e.message}`)
                                        })), reDisplayPrompt(), n("Expired token")) : e.json().then((e => {
                                            n(e.message)
                                        }))
                                    })).catch((e => {
                                        n(e)
                                    }))
                                }
                            } else n("Empty transcript")
                        }))
                    })).catch((e => n(e))) : n("No quick note template")
                })) : 401 === s.status ? (s.json().then((e => {
                    saveLog(`Export2App 401 fail 3 ${e.message} ${i.token}`)
                })), reDisplayPrompt(), n("Expired token")) : s.json().then((e => n(e.message)))
            })).catch((e => {
                n(e)
            })).finally((() => {
                s.classList.remove("loading"), a.classList.remove("loading"), s.classList.add("finishing"), a.classList.add("finishing"), setTimeout((() => {
                    s.classList.remove("finishing"), a.classList.remove("finishing")
                }), 3e3)
            }))
        } else n("Not logged in")
    }))
})), downloadTranscript = () => {
    const e = document.getElementById("meeting-name").innerText,
        t = document.getElementById("laxis-confirm-download");
    t.innerHTML = "Downloading...";
    const o = document.getElementById("highlightCheck").checked,
        n = document.getElementById("timestampCheck").checked,
        i = document.getElementById("extension").value.toString(),
        s = getTranscriptText(o, n);
    let a;
    switch (i) {
        case "pdf":
            a = () => Export2Pdf(s, e);
            break;
        case "doc":
            a = () => Export2Word(s, e);
            break;
        case "txt":
            a = () => Export2Txt(s, e);
            break;
        default:
            a = () => Export2App(o)
    }
    a().then((e => {
        "app" === i && window.open(`${domainUrl}/transcript/${e}`, "_blank")
    })).catch((e => {
        window.alert(e);
        const t = get(ERROR_SAVING) || [];
        set(ERROR_SAVING, [...t, e])
    })).finally((() => {
        t.innerHTML = "Download";
        const e = document.getElementById("laxis-downloadMenu");
        e && (e.style.display = "none")
    }))
};

function saveLog(e) {
const t = {
    message: e,
    time: (new Date).toISOString()
};
chrome.storage.local.get("logs", (function(e) {
    var o = structuredClone(e.logs);
    void 0 === o ? o = [t] : o.push(t), chrome.storage.local.set({
        logs: o
    })
}))
}