
import {
    Router
} from "express";

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


export var Routes = Router();


Routes.get('/printers', async function (Request, Response) {
    let PrinterList = await PrinterTable.findAll();

    PrinterList.sort(function (a, b) {
        if (a.name < b.name) return -1;
        if (a.name > b.name) return 1;
        return 0;
    });

    Response.send(PrinterList);
})

Routes.get('/printer/:PrinterID', async function (Request, Response) {
    Response.send(await PrinterTable.findByPk(Request.params.PrinterID));
})


Routes.post('/printer', async function (Request, Response) {
    await PrinterTable.create({
        name: Request.body.name,
        socket_addr: Request.body.socket_addr,
        socket_port: Request.body.socket_port,
        density: Request.body.density,
        type: "zpl"
    });

    Response.status(200);
    Response.end();
})


Routes.put('/printer', async function (Request, Response) {
    await PrinterTable.update({
        name: Request.body.name,
        socket_addr: Request.body.socket_addr,
        socket_port: Request.body.socket_port,
        density: Request.body.density,
        type: "ZPL"
    }, {
        where: {
            id: Request.body.id
        }
    });

    Response.status(200);
    Response.end();
})


Routes.delete('/printer/:PrinterID', async function (Request, Response) {
    await PrinterTable.destroy({
        where: {
            id: Request.params.PrinterID
        }
    });

    Response.status(200);
    Response.end();
})
