"use strict";
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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const svg_1 = require("../../utilities/svg");
const user_1 = require("../../utilities/user");
const paths_1 = require("../../paths");
const router = express_1.default.Router();
router.post("/characters", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { name, username, svg } = req.body;
        // Validate input
        if (!name || !username || !svg) {
            return res.status(400).json({ error: "Missing name, username, or SVG" });
        }
        // Check if the user exists
        if (!(yield (0, user_1.userExists)(username))) {
            return res.status(400).json({ error: "User does not exist" });
        }
        // Create character directory if it doesn't exist
        const characterName = (0, svg_1.validateName)(name);
        const userDir = `${paths_1.PROFILES_PATH}/${username}`;
        yield (0, svg_1.createCharacterDirectory)(userDir, characterName);
        // Generate a unique filename for the SVG
        const svgPath = yield (0, svg_1.generateUniqueSVGPath)(`${userDir}/${characterName}`);
        if (svgPath === "ERROR_NO_CHARACTER_DIRECTORY") {
            return res
                .status(404)
                .json({ error: "Character directory does not exist" });
        }
        // Extract the SVG content from the data URL
        const svgContent = decodeURIComponent(svg.split(",")[1]);
        // Write the SVG content to a file
        yield (0, svg_1.writeSVGToFile)(svgPath, svgContent);
        res.json({ success: true });
    }
    catch (err) {
        console.error(err);
        res.status(500).json({ error: "Something went wrong!" });
    }
}));
router.post("/number-entries", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const { char, username } = req.body;
    try {
        if (!char || !username) {
            return res
                .status(400)
                .json({ error: "Missing characterName or username" });
        }
        const validCharName = (0, svg_1.validateName)(char);
        const characterDir = `${paths_1.PROFILES_PATH}/${username}/${validCharName}`;
        const numberOfEntries = yield (0, svg_1.numberOfFiles)(characterDir);
        res.json({ numberOfEntries: numberOfEntries });
    }
    catch (err) {
        console.error(err);
        res.status(500).json({ error: "Something went wrong!" });
    }
}));
router.post("/handwriting", (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
    const { username, text, scaleFactor, defects } = req.body;
    if (!text) {
        return res.status(400).json({ error: "Missing text" });
    }
    try {
        // Split by lines
        const lines = text.split("\n");
        let totalMissing = []; // Expected to be one dim array
        let totalPaths = []; // Expected to be two dim array
        for (let line of lines) {
            const { paths, missing } = yield (0, svg_1.svgLinePathNames)(username, line);
            totalMissing.push(...missing);
            totalPaths.push(paths);
        }
        // If there is missing char
        if (totalMissing.length > 0) {
            // Remove duplicates
            totalMissing = [...new Set(totalMissing)];
            return res
                .status(404)
                .json({ error: `Missing character/s ${totalMissing.join(",")}` });
        }
        // Generate a larger
        const generatSVGOptions = {
            paths: totalPaths,
            scaleFactor: scaleFactor !== null && scaleFactor !== void 0 ? scaleFactor : 1,
            defects: defects,
        };
        const { serverFilePath, totalHeight, totalWidth } = yield (0, svg_1.generateSvg)(generatSVGOptions);
        // Read the SVG files
        return res.json({
            svgLink: serverFilePath,
            dim: { width: Math.ceil(totalWidth), height: Math.ceil(totalHeight) },
        });
    }
    catch (err) {
        console.error(err);
        res.status(500).json({ error: "Unable to create the handwriting" });
    }
}));
router.post("/print", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        const printingStatus = yield (0, svg_1.printSVG)(`${paths_1.STATIC_PATH}/generated.svg`);
        res.status(printingStatus.success ? 200 : 500).json({
            error: (_a = printingStatus.message.split("\n")[1]) !== null && _a !== void 0 ? _a : "Something went wrong",
        });
    }
    catch (e) {
        return res.status(500).json({ error: e });
    }
}));
router.get("/random-glyph/:username/:charName", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _b, _c;
    let { username, charName } = req.params;
    if (!username || !charName) {
        return res.status(400).json({ error: "Missing username or char" });
    }
    try {
        // remove the double quotes form the charName
        charName = charName === "dot" ? "." : charName;
        const validCharName = (0, svg_1.validateName)(charName);
        const fullPath = yield (0, svg_1.getRandomEntityPath)(username, validCharName);
        const svgContent = yield (0, svg_1.fetchSVGContent)(fullPath);
        const { parent } = yield (0, svg_1.parseSVG)(svgContent);
        const width = (_b = parseFloat(parent.getAttribute("width"))) !== null && _b !== void 0 ? _b : 0;
        const height = (_c = parseFloat(parent.getAttribute("height"))) !== null && _c !== void 0 ? _c : 0;
        const warpedSvg = (0, svg_1.warpSvg)(svgContent, width, height);
        res.json(warpedSvg);
    }
    catch (err) {
        console.error(err);
        res.status(500).json({ error: "Something went wrong!" });
    }
}));
exports.default = router;