
import {
    Router
} from "express";

import {
    Template as TemplateTabel,
    Element as ElementTable,
    Variable as VariableTable
} from "../sequelize/template.model.mjs";

import {
    Queue as QueueTable
} from "../sequelize/queue.model.mjs";

import {
    Printer as PrinterTable
} from "../sequelize/printer.model.mjs";

import {
    Template as TemplateTable
} from "../sequelize/template.model.mjs";


export var Routes = Router();


Routes.get("/printer", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();

    Response.render(`ui/settings.printers.njk`, {
        QueueList
    });
});

Routes.get("/media", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();

    Response.render(`ui/settings.media.njk`, {
        QueueList
    });
});

Routes.get("/queue", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();

    Response.render(`ui/settings.queues.njk`, {
        QueueList
    });
});

Routes.get("/apps", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();

    Response.render(`ui/settings.apps.njk`, {
        QueueList
    });
});

Routes.get("/queue/:QueueID", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();
    let printers = await PrinterTable.findAll();
    let templates = await TemplateTable.findAll();
    let queueData = await QueueTable.findByPk(Request.params.QueueID);

    Response.render(`ui/queue.njk`, {
        QueueID: Request.params.QueueID,
        QueueList,
        printers,
        templates: templates,
        queueData: queueData
    })
});

Routes.get("/templates", async (Request, Response) => {
    let QueueList = await QueueTable.findAll();

    Response.render(`ui/settings.templates.njk`, {
        QueueList
    })
});

Routes.get("/template/:templateId", async (Request, Response) => {
    let queueList = await QueueTable.findAll();
    let template = await TemplateTabel.findByPk(Request.params.templateId, {
        include: [
            VariableTable,
            ElementTable
        ]
    });

    // convert to raw object
    template = JSON.parse(JSON.stringify(template));

    if (template == null) {
        Response.render(`ui/error.njk`, {
            Error: {
                Code: "404",
                Title: "Template not found.",
                Message: "The template you're looking for does'nt exist.",
                Link: "/templates"
            }
        })
    } else {
        Response.render(`ui/settings.template.njk`, {
            template,
            queueList
        })
    }
});