import { postData, verifyLogin } from "./client.js";

if (!verifyLogin("professor")) window.location.href = "/home"

const sectionsHead = document.querySelector("#sections");

getCourses();
generateYears();

async function getCourses() {
    const coursesSelect = document.querySelector("#courses");

    const courses = await postData("/getCourses", {}, window.localStorage.getItem("token"));

    courses.forEach(course => {
        coursesSelect.innerHTML += `<option value="${course.Subject} ${course.Number}">${course.Subject} ${course.Number}</option>`;
    });
}

function generateYears() {
    const yearSelect = document.querySelector("#year");
    for (let i = 0; i < 5; i++) {
        yearSelect.innerHTML += `<option value="${new Date().getFullYear() + i}">${new Date().getFullYear() + i}</option>`;
    }
}

const form = document.querySelector("#createSectionForm");

if (form !== null) form.onsubmit = async e => {
    e.preventDefault();
    console.log("here");
    const data = new FormData(form);

    let daysMask = 0;
    data.getAll("days").forEach(day => {
        switch (day) {
            case "saturday":
                daysMask += 1;
                break;
            case "friday":
                daysMask += 2;
                break;
            case "thursday":
                daysMask += 4;
                break;
            case "wednesday":
                daysMask += 8;
                break;
            case "tuesday":
                daysMask += 16;
                break;
            case "monday":
                daysMask += 32;
                break;
            case "sunday":
                daysMask += 64;
                break;
            default:
                console.log(`Unknown day ${day}`);
                break;
        }
    })

    console.log(data.get("courses"));
    const subject = data.get("courses").split(" ")[0];
    const number = data.get("courses").split(" ")[1];

    const startTime = data.get("startTime");
    const endTime = data.get("endTime");

    const startDate = data.get("startDate");
    const endDate = data.get("endDate");

    const term = data.get("semester") + data.get("year");

    const resultObject = await postData("/createSection", {
        subject: subject,
        number: number,
        days: daysMask,
        startDate: startDate,
        endDate: endDate,
        startTime: startTime,
        endTime: endTime,
        term: term
    }, window.localStorage.getItem("token"));
    alert(resultObject.message);
}
