"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const data_source_1 = require("../data-source");
const Classes_1 = require("../entity/Classes");
const ClassDetail_1 = require("../entity/ClassDetail");
const ClassNumber_1 = require("../entity/ClassNumber");
const typeorm_1 = require("typeorm");
const auth_1 = require("../middleware/auth");
const uuid_1 = require("uuid");
// import nodemailer from 'nodemailer';
// import icalToolkit from 'ical-toolkit';
const router = (0, express_1.Router)();
router.get('/classes', auth_1.authentificationToken, async (req, res) => {
    try {
        const repo = data_source_1.AppDataSource.getRepository(Classes_1.Classes);
        console.log(req.query.startDate);
        //const startDate = req.query.startDate === undefined ? null : new Date(req.query?.startDate?.toString());
        //const endDate = req.query.endDate === undefined ? null : new Date(req.query?.endDate?.toString());

        let startDate = null;
        let endDate = null;

        // const startDate = req.query.startDate === undefined ? null : new Date(req.query?.startDate?.toString());
        // const endDate = req.query.endDate === undefined ? null : new Date(req.query?.endDate?.toString());

        if (req.query.startDate && req.query.startDate !== "null") {
          startDate = new Date(req.query.startDate.toString());
        }

        if (req.query.endDate && req.query.endDate !== "null") {
          endDate = new Date(req.query.endDate.toString());
        }

        console.log(startDate);
        console.log(endDate);
        let classes;
        if (startDate && endDate) {
            classes = await repo.find({
                where: { endDate: (0, typeorm_1.LessThan)(endDate), startDate: (0, typeorm_1.MoreThan)(startDate) },
                relations: [
                    'client',
                    'TeachingMode',
                    'ClassesDetails',
                    'ClassesDetails.Course',
                    'ClassesDetails.Students',
                    'ClassesDetails.Students.TypeStudent',
                    'ClassesDetails.Students.TitleStudent'
                ]
            });
        }
        else {
            classes = await repo.find({
                relations: [
                    'client',
                    'User',
                    'TeachingMode',
                    'ClassesDetails',
                    'ClassesDetails.Course',
                    'ClassesDetails.Students',
                    'ClassesDetails.Students.TypeStudent',
                    'ClassesDetails.Students.TitleStudent'
                ]
            });
        }
        res.send(classes);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
router.get('/class/:id', auth_1.authentificationToken, async (req, res) => {
    try {
        const repo = data_source_1.AppDataSource.getRepository(Classes_1.Classes);
        const classItem = await repo.findOne({
            where: { id: parseInt(req.params.id) },
            relations: [
                'client',
                'User',
                'client.Addresses',
                'client.Students',
                'client.Students.TypeStudent',
                'TeachingMode',
                'ClassesDetails',
                'ClassesDetails.Course',
                'ClassesDetails.Students',
                'ClassesDetails.Students.TypeStudent',
                'ClassesDetails.Students.TitleStudent'
            ]
        });
        res.send(classItem);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
// Additional routes like addclass, updateclass, deleteclass would go here...
exports.default = router;
router.post('/addclass', auth_1.authentificationToken, async (req, res) => {
    try {
        const classNumberRepo = data_source_1.AppDataSource.getRepository(ClassNumber_1.ClassNumber);
        const lastCN = await classNumberRepo.createQueryBuilder('CN').orderBy('CN.id', 'DESC').getOne();
        const nextCN = new ClassNumber_1.ClassNumber();
        nextCN.id = (lastCN?.id || 0) + 1;
        await classNumberRepo.save(nextCN);
        const classRepo = data_source_1.AppDataSource.getRepository(Classes_1.Classes);
        const detailRepo = data_source_1.AppDataSource.getRepository(ClassDetail_1.ClassDetail);
        const newClass = classRepo.create(req.body)[0];
        newClass.meetingUUID = (0, uuid_1.v1)();
        newClass.number = nextCN.id.toString();
        const savedClass = await classRepo.save(newClass);
        const details = req.body.ClassesDetails || [];
        for (const element of details) {
            element.Class = { id: savedClass.id };
            const classDetail = detailRepo.create(element);
            await detailRepo.save(classDetail);
        }
        const finalClass = await classRepo.findOne({
            where: { id: savedClass.id },
            relations: [
                'client',
                'client.Students',
                'client.Students.TypeStudent',
                'TeachingMode',
                'ClassesDetails',
                'ClassesDetails.Course',
                'ClassesDetails.Students',
                'ClassesDetails.Students.TypeStudent',
                'ClassesDetails.Students.TitleStudent'
            ]
        });
        // Optional: ClassMeetingNotify(finalClass, 'CONFIRMED');
        res.send(finalClass);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
router.put('/updateclass/:id', auth_1.authentificationToken, async (req, res) => {
    try {
        const classRepo = data_source_1.AppDataSource.getRepository(Classes_1.Classes);
        const detailRepo = data_source_1.AppDataSource.getRepository(ClassDetail_1.ClassDetail);
        const cls = await classRepo.findOne({
            where: { id: parseInt(req.params.id) },
            relations: ['ClassesDetails']
        });
        for (const detail of cls.ClassesDetails) {
            await detailRepo.delete(detail.id);
        }
        classRepo.merge(cls, req.body);
        cls.modifyDate = new Date();
        const updated = await classRepo.save(cls);
        for (const detail of req.body.ClassesDetails) {
            detail.id = null;
            detail.Class = { id: updated.id };
            const newDetail = detailRepo.create(detail);
            await detailRepo.save(newDetail);
        }
        const finalClass = await classRepo.findOne({
            where: { id: updated.id },
            relations: [
                'client',
                'client.Students',
                'client.Students.TypeStudent',
                'TeachingMode',
                'ClassesDetails',
                'ClassesDetails.Course',
                'ClassesDetails.Students',
                'ClassesDetails.Students.TypeStudent',
                'ClassesDetails.Students.TitleStudent'
            ]
        });
        // Optional: ClassMeetingNotify(finalClass, 'CONFIRMED');
        res.send(updated);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
router.delete('/deleteclass/:id', auth_1.authentificationToken, async (req, res) => {
    try {
        const repo = data_source_1.AppDataSource.getRepository(Classes_1.Classes);
        const cls = await repo.findOne({ where: { id: parseInt(req.params.id) } });
        cls.canceled = true;
        await repo.save(cls);
        // Optional: ClassMeetingNotify(cls, 'CANCELLED');
        res.send(true);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
async function GetClassesDetailsDescription(ClassesDetails) {
    let description = '';
    ClassesDetails.forEach(cd => {
        description += '($ ' + cd.cost + ') ' + cd.Course.title + '\r\n';
    });
    return description;
}
// function ClassMeetingNotify(c: Classes, status: string) {
//   GetClassesDetailsDescription(c.ClassesDetails).then(async result => {
//     let description = result;
//     if (c.note != null) description += 'Notes: ' + c.note;
//     let builder = icalToolkit.createIcsFileBuilder();
//     builder.spacers = true;
//     builder.NEWLINE_CHAR = '\r\n';
//     builder.throwError = false;
//     builder.ignoreTZIDMismatch = true;
//     builder.timezone = 'america/new_york';
//     builder.tzid = 'america/new_york';
//     builder.method = 'REQUEST';
//     builder.events.push({
//       start: c.startDate,
//       end: c.endDate,
//       transp: 'OPAQUE',
//       summary: c.client.name,
//       location: `${c.address1}, ${c.address2} ${c.city}, ${c.state}, ${c.zip}`,
//       uid: c.meetingUUID,
//       description: description,
//       status: status,
//       attendees: [
//         { name: 'Linda Cannon', email: 'llcannon757@gmail.com' },
//         { name: 'Linda Cannon', email: 'msds@cox.net' },
//         { name: 'Linda Cannon', email: '7181515@cox.net' },
//         { name: 'msds classes', email: 'msdsclasses@outlook.com' }
//       ]
//     });
//     const icsFileContent = builder.toString();
//     if (icsFileContent instanceof Error) return;
//     let transporter = nodemailer.createTransport({
//       host: 'smtp.office365.com',
//       port: 587,
//       secure: false,
//       auth: {
//         user: 'cloud.msdssafety@outlook.com',
//         pass: 'Lopez90200'
//       }
//     });
//     const message = {
//       from: 'gaetan90@outlook.fr',
//       to: ['gaetan90@outlook.fr'],
//       subject: `${c.number} - ${c.client.name} Phone: ${c.client.phoneNumber} EmergPhone: ${c.client.contactPhoneNumber} - ${description}`,
//       text: description,
//       icalEvent: {
//         filename: 'invitation.ics',
//         method: 'request',
//         content: icsFileContent
//       }
//     };
//     transporter.sendMail(message);
//   });
// }
