var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx } from "react/jsx-runtime";
import { useContext } from "react";
import { Button } from "@/components/ui/button";
import { useUser } from "@web/user/UserProvider";
import { useNavigate } from "react-router-dom";
import { useToast } from "@/components/hooks/use-toast";
import { errorCount, TemplateContext, TemplateErrorContext, } from "./TemplateProvider";
export const SaveButton = () => {
    return _jsx(SavePublishButton, { t: "save" });
};
export const PublishButton = () => {
    return _jsx(SavePublishButton, { t: "publish" });
};
const SavePublishButton = ({ t }) => {
    const { user, sessionKey } = useUser();
    const key = sessionKey();
    const navigate = useNavigate();
    const { toast } = useToast();
    const { template, setTemplate } = useContext(TemplateContext);
    const { errors } = useContext(TemplateErrorContext);
    return (_jsx(Button, { onClick: (_) => {
            if (user === null || key === undefined) {
                navigate("/signin");
            }
            else {
                savePublish(user, key, template, errors, t).then((res) => {
                    const [ok, json] = res;
                    if (ok) {
                        toast({ title: "Success" });
                        if (t === "save") {
                            handleSave(json);
                        }
                        else {
                            handlePublish(json, template, setTemplate);
                        }
                    }
                    else {
                        toast({
                            title: "Error",
                            description: decodeError(json),
                            variant: "destructive",
                        });
                    }
                });
            }
        }, variant: t === "save" ? "outline" : "default", children: t === "save" ? "Save Draft" : "Publish Template" }));
};
const savePublish = (username, sessionKey, template, errors, t) => __awaiter(void 0, void 0, void 0, function* () {
    if (t === "publish" && errorCount(errors) > 0) {
        return [false, "PUBLISH_ERROR"];
    }
    if (t === "save" && (errors.language === true || errors.title !== null)) {
        return [false, "SAVE_ERROR"];
    }
    const apiPath = "/api/" + t;
    const toSubmit = {
        sessionKey: sessionKey,
        username: username,
        template: Object.assign(Object.assign({}, template), { username: username, date: "" }),
    };
    const request = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(toSubmit),
    };
    try {
        const response = yield fetch(apiPath, request);
        const json = yield response.json();
        return [response.ok, json];
    }
    catch (error) {
        return [false, "NETWORK"];
    }
});
const decodeError = (message) => {
    switch (message) {
        case "INVALID_SESSION_KEY":
        case "INVALID_USER":
            return "Invalid session, Please login again.";
        case "DB_ERR":
            return "Server error. Please try again later.";
        case "PUBLISH_ERROR":
            return "Please ensure that your template is error-free before publishing.";
        case "SAVE_ERROR":
            return "Unable to save draft without first specifying template title and language.";
        default:
            return "Network errror. Unable to connect to the server.";
    }
};
const handlePublish = (json, template, setTemplate) => {
    const { published_id, version_id } = json;
    setTemplate(Object.assign(Object.assign({}, template), { publishedId: published_id, versionId: version_id }));
};
const handleSave = (json) => {
    const { id } = JSON.parse(json);
};
