
import {
    Router
} from "express";

import {
    Medium as MediaTable    
} from "../sequelize/media.model.mjs";

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


export var Routes = Router();


Routes.get('/media', async function (Request, Response)
{
    let MediaList = await MediaTable.findAll();

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

    Response.send(MediaList);
})


Routes.get('/medium/:MediumID', async function (Request, Response)
{
    Response.send(await MediaTable.findByPk(Request.params.MediumID));
})


Routes.post('/medium', async function (Request, Response)
{
    let NewMedium = await MediaTable.create({
        name: Request.body.name,
        columns: Request.body.columns,
        spacing: Request.body.spacing,
        width: Request.body.width
    });

    Response.status(200);
    Response.send(NewMedium);
})


Routes.put('/medium', async function (Request, Response)
{
    let Medium = await MediaTable.findByPk(Request.body.mediumId);

    await Medium.update({
        name: Request.body.name,
        columns: Request.body.columns,
        spacing: Request.body.spacing,
        width: Request.body.width
    });

    Response.status(200);
    Response.send(Medium);
})


Routes.delete('/medium', async function (Request, Response)
{
    let Medium = await MediaTable.findByPk(Request.body.mediumId);

    await Medium.destroy();

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


Routes.put('/medium/label', async function (Request, Response)
{
    let Medium = await MediaTable.findByPk(Request.body.mediumId);
    let Label = await LabelTable.findByPk(Request.body.labelId);

    await Medium.addLabel(Label);

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


Routes.delete('/medium/label', async function (Request, Response)
{
    let Medium = await MediaTable.findByPk(Request.body.mediumId);
    let Label = await LabelTable.findByPk(Request.body.labelId);

    await Medium.removeLabel(Label);

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