// Browser queue and synchronization for offline inspection entry.

window.createInspectionOfflineQueue = function createInspectionOfflineQueue(scope) {
    "use strict";

    if (typeof scope !== "string" || !scope.trim()) {
        throw new TypeError("An application and user scope is required.");
    }

    const databaseName = "phprunner-offline-add-v1";
    const storeName = "submissions";

    let activeSync;
    let stopSync;

    function transact(mode, operation) {
        return new Promise((resolve, reject) => {
            const open = indexedDB.open(databaseName, 1);

            open.onupgradeneeded = () => {
                const store = open.result.createObjectStore(
                    storeName,
                    { keyPath: "id" }
                );

                store.createIndex("scope", "scope");
            };

            open.onerror = () => reject(open.error);

            open.onblocked = () => {
                reject(
                    new Error(
                        "Offline storage is blocked by another browser tab."
                    )
                );
            };

            open.onsuccess = () => {
                const db = open.result;

                try {
                    const tx = db.transaction(storeName, mode);

                    tx.onabort = () => {
                        db.close();

                        reject(
                            tx.error ||
                            new Error(
                                "Offline storage transaction was aborted."
                            )
                        );
                    };

                    const request = operation(
                        tx.objectStore(storeName)
                    );

                    tx.oncomplete = () => {
                        db.close();
                        resolve(request.result);
                    };
                } catch (error) {
                    db.close();
                    reject(error);
                }
            };
        });
    }

    async function enqueue(form, payload) {
        const entry = {
            id: crypto.randomUUID(),
            scope: scope,
            form: form,
            createdAt: Date.now(),
            payload: payload
        };

        await transact(
            "readwrite",
            store => store.add(entry)
        );

        return entry.id;
    }

    function pending() {
        return transact(
            "readonly",
            store => store.index("scope").getAll(scope)
        );
    }

    function start(options) {
        const ping = options.ping;
        const send = options.send;
        const onProgress = options.onProgress || function () {};

        if (stopSync) {
            throw new Error(
                "Offline synchronization is already running for this queue."
            );
        }

        let stopped = false;

        async function drain() {
            const entries = await pending();

            entries.sort(
                (first, second) =>
                    first.createdAt - second.createdAt
            );

            if (stopped || entries.length === 0) {
                return;
            }

            if (await ping() !== true) {
                onProgress({
                    state: "waiting",
                    remaining: entries.length
                });

                return;
            }

            let sent = 0;
            let blocked = 0;

            for (const [index, entry] of entries.entries()) {
                if (stopped) {
                    return;
                }

                onProgress({
                    state: "sending",
                    current: index + 1,
                    total: entries.length
                });

                const result = await send(entry);

                if (result && result.blocked === true) {
                    blocked++;
                    continue;
                }

                if (
                    !result ||
                    result.saved !== true ||
                    result.submissionId !== entry.id
                ) {
                    onProgress({
                        state: "waiting",
                        remaining: entries.length - sent
                    });

                    return;
                }

                await transact(
                    "readwrite",
                    store => store.delete(entry.id)
                );

                sent++;
            }

            if (blocked > 0) {
                onProgress({
                    state: "error",
                    error: new Error(
                        blocked +
                        " inspection(s) remain queued because an earlier " +
                        "server save was not confirmed."
                    )
                });
            } else {
                onProgress({
                    state: "synced",
                    sent: sent
                });
            }
        }

        function sync() {
            if (stopped) {
                return Promise.resolve();
            }

            if (!activeSync) {
                const work = navigator.locks
                    ? navigator.locks.request(
                        databaseName + ":" + scope,
                        drain
                    )
                    : drain();

                activeSync = work
                    .catch(error => {
                        onProgress({
                            state: "error",
                            error: error
                        });
                    })
                    .finally(() => {
                        activeSync = undefined;
                    });
            }

            return activeSync;
        }

        window.addEventListener("online", sync);
        window.addEventListener("focus", sync);

        const timer = window.setInterval(
            sync,
            30000
        );

        stopSync = function () {
            stopped = true;

            window.removeEventListener("online", sync);
            window.removeEventListener("focus", sync);
            window.clearInterval(timer);

            stopSync = undefined;
        };

        void sync();

        return {
            sync: sync,
            stop: stopSync
        };
    }

    return {
        enqueue: enqueue,
        pending: pending,
        start: start
    };
};


window.pingInspectionServer = async function pingInspectionServer(
    expectedScope
) {
    const controller = new AbortController();

    const timeout = window.setTimeout(
        () => controller.abort(),
        4000
    );

    try {
        const response = await fetch(
            "offline_ping.php",
            {
                credentials: "same-origin",
                cache: "no-store",
                redirect: "error",
                signal: controller.signal
            }
        );

        if (!response.ok) {
            return false;
        }

        const result = await response.json();

        return (
            result.ready === true &&
            result.scope === expectedScope
        );
    } catch (error) {
        return false;
    } finally {
        window.clearTimeout(timeout);
    }
};


window.uploadInspectionFindingPhotos =
async function uploadInspectionFindingPhotos(
    photos,
    formStamp
) {
    if (!formStamp) {
        throw new Error(
            "A PHPRunner form stamp is required."
        );
    }

    const query = new URLSearchParams({
        _action: "POST",
        table: "findings",
        field: "photos",
        pageType: "add",
        page: "list",
        formStamp: formStamp,
        newmupload: "true"
    });

    const uploaded = [];

    for (const photo of photos) {
        const body = new FormData();

        body.append(
            "files[]",
            photo,
            photo.name
        );

        const controller = new AbortController();

        const timeout = window.setTimeout(
            () => controller.abort(),
            30000
        );

        try {
            const response = await fetch(
                "mfhandler.php?" + query.toString(),
                {
                    method: "POST",
                    credentials: "same-origin",
                    redirect: "error",
                    body: body,
                    signal: controller.signal
                }
            );

            if (!response.ok) {
                throw new Error(
                    "Photo upload failed (HTTP " +
                    response.status +
                    ")."
                );
            }

            const result = await response.json();
            const file = result.files &&
                result.files.length
                ? result.files[0]
                : null;

            if (
                !result.files ||
                result.files.length !== 1 ||
                !file ||
                file.error ||
                !file.url
            ) {
                throw new Error(
                    "PHPRunner did not confirm the photo upload."
                );
            }

            uploaded.push(
                Object.assign(
                    {},
                    file,
                    { isNew: true }
                )
            );
        } finally {
            window.clearTimeout(timeout);
        }
    }

    return uploaded;
};


window.sendQueuedInspection =
async function sendQueuedInspection(entry) {
    if (entry.form !== "inspections") {
        throw new Error(
            "This sender only handles inspections."
        );
    }

    const propertyAddress =
        entry.payload.property_address;

    const inspectionDate =
        entry.payload.inspection_date;

    const notes =
        entry.payload.notes;

    const findings =
        entry.payload.findings || [];

    const checkpointKey =
        "inspection-sync:" +
        entry.scope +
        ":" +
        entry.id;

    let checkpoint;

    try {
        checkpoint = JSON.parse(
            localStorage.getItem(checkpointKey) || "null"
        );
    } catch (error) {
        checkpoint = null;
    }

    checkpoint = checkpoint || {
        inspectionId: null,
        nextFinding: 0,
        pendingWrite: null
    };

    function saveCheckpoint() {
        localStorage.setItem(
            checkpointKey,
            JSON.stringify(checkpoint)
        );
    }

    async function post(url, fields) {
        const body = new FormData();

        for (const [name, value] of Object.entries(fields)) {
            body.append(
                name,
                String(value)
            );
        }

        const controller = new AbortController();

        const timeout = window.setTimeout(
            () => controller.abort(),
            30000
        );

        try {
            const response = await fetch(
                url,
                {
                    method: "POST",
                    credentials: "same-origin",
                    redirect: "error",
                    body: body,
                    signal: controller.signal
                }
            );

            if (!response.ok) {
                throw new Error(
                    "PHPRunner returned HTTP " +
                    response.status +
                    "."
                );
            }

            const responseText =
                await response.text();

            /*
             * PHPRunner may HTML-encode the JSON response.
             * Decode it before parsing.
             */
            const decoder =
                document.createElement("textarea");

            decoder.innerHTML = responseText;

            return JSON.parse(decoder.value);
        } finally {
            window.clearTimeout(timeout);
        }
    }

    /*
     * Do not repeat a write when the previous request may have
     * reached the server but its response was not confirmed.
     */
    if (checkpoint.pendingWrite) {
        return {
            blocked: true
        };
    }

    if (checkpoint.inspectionId === null) {
        checkpoint.pendingWrite = "inspection";
        saveCheckpoint();

        const result = await post(
            "inspections_add.php?page=add&submit=1",
            {
                value_property_address_1:
                    propertyAddress,

                value_inspection_date_1:
                    inspectionDate,

                type_inspection_date_1:
                    "date11",

                value_notes_1:
                    notes || "",

                id: 1,
                editType: 3,
                a: "added",
                rndVal: Math.random()
            }
        );

        const inspectionId = Number(
            result.keys &&
            result.keys.length
                ? result.keys[0]
                : NaN
        );

        const detailKeys =
            result.detKeys &&
            result.detKeys.findings
                ? result.detKeys.findings
                : null;

        const detailMasterId = Number(
            detailKeys
                ? detailKeys.masterkey1
                : NaN
        );

        if (
            result.success !== true ||
            !Number.isSafeInteger(inspectionId) ||
            inspectionId <= 0 ||
            detailMasterId !== inspectionId
        ) {
            throw new Error(
                "PHPRunner did not confirm the new inspection ID."
            );
        }

        checkpoint.inspectionId = inspectionId;
        checkpoint.pendingWrite = null;

        saveCheckpoint();
    }

    while (
        checkpoint.nextFinding < findings.length
    ) {
        const finding =
            findings[checkpoint.nextFinding];

        const rowId =
            finding.rowId;

        if (
            !Number.isSafeInteger(rowId) ||
            rowId <= 0
        ) {
            throw new Error(
                "The queued finding is missing its " +
                "PHPRunner inline row ID."
            );
        }

        const formStamp = crypto
            .randomUUID()
            .replace(/-/g, "")
            .slice(0, 15);

        const photos =
            await window.uploadInspectionFindingPhotos(
                finding.photos || [],
                formStamp
            );

        checkpoint.pendingWrite =
            "finding " +
            (checkpoint.nextFinding + 1);

        saveCheckpoint();

        const fields = {};

        fields["value_room_" + rowId] =
            finding.room;

        fields["value_description_" + rowId] =
            finding.description;

        fields["value_photos_" + rowId] =
            JSON.stringify(photos);

        fields["formStamp_photos_" + rowId] =
            formStamp;

        fields.id = rowId;
        fields.editType = "inline";
        fields.a = "added";
        fields.page = "list";
        fields.spreadsheetGrid = 0;
        fields.hostPageName = "list";
        fields.mastertable = "inspections";
        fields.masterkey1 =
            checkpoint.inspectionId;
        fields.masterpagetype = "add";
        fields.rndVal = Math.random();

        const result = await post(
            "findings_add.php?submit=1&inline=1",
            fields
        );

        const findingId = Number(
            result.keys &&
            result.keys.length
                ? result.keys[0]
                : NaN
        );

        const savedInspectionId = Number(
            result.rawVals
                ? result.rawVals.inspection_id
                : NaN
        );

        if (
            result.success !== true ||
            !Number.isSafeInteger(findingId) ||
            findingId <= 0 ||
            savedInspectionId !==
                checkpoint.inspectionId
        ) {
            throw new Error(
                "PHPRunner did not confirm the finding save."
            );
        }

        checkpoint.nextFinding++;
        checkpoint.pendingWrite = null;

        saveCheckpoint();
    }

    localStorage.removeItem(checkpointKey);

    return {
        saved: true,
        submissionId: entry.id
    };
};


/*
 * The status element is created only when there is a message.
 * This prevents an empty blue notification area.
 */
window.ensureInspectionOfflineStatus =
function ensureInspectionOfflineStatus() {
    let status = document.querySelector(
        "[data-inspection-offline-status]"
    );

    if (status) {
        return status;
    }

    status = document.createElement("div");

    status.setAttribute(
        "data-inspection-offline-status",
        ""
    );

    status.setAttribute(
        "role",
        "status"
    );

    status.setAttribute(
        "aria-live",
        "polite"
    );

    status.className =
        "alert alert-info";

    status.style.position = "sticky";
    status.style.top = "0";
    status.style.zIndex = "1020";
    status.style.marginTop = "16px";
    status.style.marginBottom = "16px";

    const heading =
        document.querySelector("h1, h2");

    if (heading) {
        heading.insertAdjacentElement(
            "afterend",
            status
        );
    } else {
        const pageContainer =
            document.querySelector(
                ".r-body, .container, main"
            );

        if (pageContainer) {
            pageContainer.insertBefore(
                status,
                pageContainer.firstChild
            );
        } else if (document.body) {
            document.body.insertBefore(
                status,
                document.body.firstChild
            );
        }
    }

    return status;
};


window.showInspectionOfflineStatus =
function showInspectionOfflineStatus(
    message,
    style
) {
    const status =
        window.ensureInspectionOfflineStatus();

    status.textContent = message;

    status.className =
        "alert alert-" +
        (style || "info");

    status.style.display = "block";
};


window.showInspectionWaitingCount =
function showInspectionWaitingCount(count) {
    const label =
        count === 1
            ? "inspection"
            : "inspections";

    window.showInspectionOfflineStatus(
        count +
        " " +
        label +
        " saved on this device and waiting to sync.",
        "warning"
    );
};


/*
 * Creates one synchronization runtime for the current browser page.
 * Calling this function again returns the existing runtime.
 */
window.ensureInspectionOfflineRuntime =
function ensureInspectionOfflineRuntime(scope) {
    const existing =
        window.__inspectionOfflineRuntime;

    if (existing) {
        if (existing.scope !== scope) {
            throw new Error(
                "The offline runtime was started with a different scope."
            );
        }

        return existing;
    }

    const queue =
        window.createInspectionOfflineQueue(scope);

    const listeners = new Set();
    let lastProgress = null;

    function notify(progress) {
        lastProgress = progress;

        if (progress.state === "sending") {
            window.showInspectionOfflineStatus(
                "Sending " +
                progress.current +
                " of " +
                progress.total +
                "...",
                "info"
            );
        } else if (
            progress.state === "waiting"
        ) {
            window.showInspectionWaitingCount(
                progress.remaining
            );
        } else if (
            progress.state === "synced" &&
            progress.sent > 0
        ) {
            window.showInspectionOfflineStatus(
                "Queued inspections saved to the server.",
                "success"
            );
        } else if (
            progress.state === "error"
        ) {
            window.showInspectionOfflineStatus(
                progress.error &&
                progress.error.message
                    ? progress.error.message
                    : "Offline synchronization could not finish.",
                "danger"
            );
        }

        for (const listener of listeners) {
            try {
                listener(progress);
            } catch (error) {
                console.error(error);
            }
        }
    }

    const syncController = queue.start({
        ping: function () {
            return window.pingInspectionServer(
                scope
            );
        },

        send: window.sendQueuedInspection,

        onProgress: notify
    });

    const runtime = {
        scope: scope,
        queue: queue,

        sync: function () {
            return syncController.sync();
        },

        stop: function () {
            return syncController.stop();
        },

        showStatus:
            window.showInspectionOfflineStatus,

        showWaitingCount:
            window.showInspectionWaitingCount,

        subscribe: function (listener) {
            listeners.add(listener);

            if (lastProgress) {
                listener(lastProgress);
            }

            return function () {
                listeners.delete(listener);
            };
        }
    };

    window.__inspectionOfflineRuntime =
        runtime;

    return runtime;
};


/*
 * Start synchronization on every generated page because
 * custom_functions.js is loaded on every page.
 */
(function startInspectionOfflineRuntime() {
    const start = function () {
        window.ensureInspectionOfflineRuntime(
            "home-inspection:demo"
        );
    };

    if (document.readyState === "loading") {
        document.addEventListener(
            "DOMContentLoaded",
            start,
            { once: true }
        );
    } else {
        start();
    }
})();
