let dateOptions = {month: 'short', year: 'numeric'};

document.addEventListener('DOMContentLoaded', () =>
{
    // check if the user is logged in, if not redirect to log in
        fetch('/api/user/isLoggedIn').then(res => 
        {
            if (!res.ok)
            {
                window.location.href = './';
            }
        });
    document.querySelector("#dateFromE").max = new Date().toISOString().split("T")[0];
    document.querySelector("#dateFromW").max = new Date().toISOString().split("T")[0];


    fetch("/api/timelineData/edu").then(res =>
    {
        res.json().then(json =>
        {
            if (res.ok)
            {
                for (let i = 0; i < json.length; i++)
                {
                    addEduData(json[i].ID, json[i].startPeriod, json[i].endPeriod, json[i].grade, json[i].course);
                }
                return;
            }
            document.querySelector("#edu").innerHTML = "No education data found";
        })
    });
    
    fetch("/api/timelineData/work").then(res =>
    {
        res.json().then(json =>
        {
            if (res.ok)
            {
                for (let i = 0; i < json.length; i++)
                {
                    let endPeriod = json[i].endPeriod === null ? "Present" : json[i].endPeriod;
                    addWorkData(json[i].ID, json[i].startPeriod, endPeriod, json[i].companyName, json[i].area, json[i].title);
                }
                return;
            }
            document.querySelector("#edu").innerHTML = "No education data found";
        })
    });
})

document.querySelector("#navOpen").addEventListener("click", e =>
{
    document.querySelector("nav.sideNav").style.removeProperty("width");
    document.querySelector("main.editor").style.removeProperty("margin-left");
    e.target.style.removeProperty("visibility");
});

document.querySelector("#navClose").addEventListener("click", () =>
{
    document.querySelector("nav.sideNav").style.width = "0";
    document.querySelector("main.editor").style.marginLeft = "0";
    document.querySelector("#navOpen").style.visibility = "visible";
});

document.querySelector("#addEdu").addEventListener("submit", e =>
{
    e.preventDefault();
    let data = new FormData();
    data.append("dateFrom", document.querySelector("#dateFromE").value);
    data.append("dateTo", document.querySelector("#dateToE").value);
    data.append("grade", document.querySelector("#grade").value);
    data.append("course", document.querySelector("#courseTitle").value);
    
    fetch("/api/timelineData/edu", {
        method: "POST",
        body: data,
        headers: {
            "Authentication": localStorage.getItem("token")
        }
    }).then(res => res.json().then(json => 
    {
        if (res.ok)
        {
            addEduData(json.ID, data.get("dateFrom"), data.get("dateTo"), data.get("grade"), data.get("course"), true);
            document.querySelector("#addEdu").reset();
            return;
        }

        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }

        document.querySelector("#eduError").classList.remove("hidden");
        document.querySelector("#eduError div").innerHTML = json.error;
    }));
});

document.querySelector("#addWork").addEventListener("submit", e =>
{
    e.preventDefault();
    let data = new FormData();
    data.append("dateFrom", document.querySelector("#dateFromW").value);
    data.append("dateTo", document.querySelector("#dateToW").value);
    data.append("companyName", document.querySelector("#company").value);
    data.append("area", document.querySelector("#area").value);
    data.append("title", document.querySelector("#jobTitle").value);

    fetch("/api/timelineData/work", {
        method: "POST",
        body: data,
        headers: {
            "Authentication": localStorage.getItem("token")
        }
    }).then(res => res.json().then(json =>
    {
        if (res.ok)
        {
            let endPeriod = data.get("dateTo") === null ? "Present" : data.get("dateTo ");
            addWorkData(json.ID, data.get("dateFrom"), endPeriod, data.get("companyName"), data.get("area"), data.get("title"), true);
            document.querySelector("#addEdu").reset();
            return;
        }

        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }

        document.querySelector("#eduError").classList.remove("hidden");
        document.querySelector("#eduError div").innerHTML = json.error;
    }));
});


/**
 * Switches the timeline item between edit and view mode
 * @param id the id of the timeline item
 */
function edit(id)
{
    document.querySelector("#timelineItem" + id).classList.toggle("editing");
    if (id.includes("e"))
    {
        document.querySelector("#grade" + id).toggleAttribute("disabled");
        document.querySelector("#course" + id).toggleAttribute("disabled");
        return;
    }
    document.querySelector("#companyName" + id).toggleAttribute("disabled");
    document.querySelector("#area" + id).toggleAttribute("disabled");
    document.querySelector("#jobTitle" + id).toggleAttribute("disabled");
}

/**
 * Updates the education timeline item with the given id
 * @param ID - the id of the course timeline item
 * @param startPeriod - the start date of the course
 * @param endPeriod - the end date of the course
 * @param grade - the grade of the course
 * @param course - the name of the course
 * @param prepend - whether to prepend the timeline item to the timeline
 */
function addEduData(ID, startPeriod, endPeriod, grade, course, prepend=false) 
{
    let id = ID + "e";
    let timelineItem = document.createElement("form")
    timelineItem.id = "timelineItem" + id;
    timelineItem.classList.add("timelineItem");
    timelineItem.onsubmit = e => updateEduItem(ID, e);
    timelineItem.innerHTML = `
    <div class="modifyBtnContainer">
        <button class="edit" type="button" id="edit${id}" onclick="edit('${id}')"><i class="fa-solid fa-pen-to-square"></i></button>
        <button class="delete" type="button" id="delete${id}" onclick="deleteEduItem(${ID})"><i class="fa-solid fa-trash"></i></button>
    </div>
    <div class="dateContainer formControl">
        <input type="date" name="dateFrom${id}" id="dateFrom${id}" onload="this.max = new Date().toISOString().split('T')[0]" value="${startPeriod}">
        -
        <input type="date" name="dateTo${id}" id="dateTo${id}" value="${endPeriod}">
    </div>
    <h3 class="timelineHeader" id="timelineHeader${id}">${new Date(startPeriod).toLocaleString('en-gb', dateOptions)} - ${new Date(endPeriod).toLocaleString('en-gb', dateOptions)}</h3>
    <div class="gradeContainer formControl">
        <label for="grade${id}">Grade:</label>
        <input type="text" name="grade${id}" id="grade${id}" value="${grade}" disabled>
    </div>
    <div class="formControl">
        <textarea class="courseText" name="course${id}" id="course${id}" cols="10" rows="3" disabled>${course}</textarea>
    </div>
    
    <div class="error hidden" id="eduError${id}">
        <button class="close" type="button" onclick="this.parentElement.classList.toggle('hidden');">&times;</button>
        <div></div>
    </div>
    <input type="submit" value="Change">
    `;
    if (prepend)
    {
        document.querySelector("#edu").prepend(timelineItem);
        return;
    }
    document.getElementById("edu").appendChild(timelineItem);
}

/**
 * Adds a new work timeline item to the page
 * @param ID - the id of the work timeline item
 * @param startPeriod - the start date of the job
 * @param endPeriod - the end date of the job
 * @param companyName - the name of the company
 * @param area - the area of the company
 * @param jobTitle - the job title
 * @param prepend - whether to prepend the timeline item to the timeline
 */
function addWorkData(ID, startPeriod, endPeriod, companyName, area, jobTitle, prepend=false)
{
    let id = ID + "w";
    let timelineItem = document.createElement("form")
    timelineItem.id = "timelineItem" + id;
    timelineItem.classList.add("timelineItem");
    timelineItem.onsubmit = e => updateWorkItem(ID, e);
    timelineItem.innerHTML = `
    <div class="modifyBtnContainer">
        <button class="edit" type="button" id="edit${id}" onclick="edit('${id}')"><i class="fa-solid fa-pen-to-square"></i></button>
        <button class="delete" type="button" id="delete${id}" onclick="deleteWorkItem(${ID})"><i class="fa-solid fa-trash"></i></button>
    </div>
    <div class="dateContainer formControl">
        <input type="date" name="dateFrom${id}" id="dateFrom${id}" onload="this.max = new Date().toISOString().split('T')[0]" value="${startPeriod}">
        -
        <input type="date" name="dateTo${id}" id="dateTo${id}" value="${endPeriod === 'Present' ? '' : endPeriod}">
    </div>
    <h3 class="timelineHeader" id="timelineHeader${id}">${new Date(startPeriod).toLocaleString('en-gb', dateOptions)} - ${endPeriod === 'Present' ? '' : new Date(endPeriod).toLocaleString('en-gb', dateOptions)}</h3>
    <div class="companyAreaContainer formControl">
        <input type="text" name="companyName${id}" id="companyName${id}" value="${companyName}" disabled>
        -
        <input type="text" name="area${id}" id="area${id}" value="${area}" disabled>                      
    </div>
    <div class="formControl">
        <textarea class="jobTitleText" name="jobTitle${id}" id="jobTitle${id}" cols="10" rows="3" disabled>${jobTitle}</textarea>
    </div>
    
    <div class="error hidden" id="workError${id}">
        <button class="close" type="button" onclick="this.parentElement.classList.toggle('hidden');">&times;</button>
        <div></div>
    </div>
    <input type="submit" value="Change">
	`;
    if (prepend)
    {
        document.querySelector("#work").prepend(timelineItem);
        return;
    }
    
    document.getElementById("work").appendChild(timelineItem);
}

/**
 * Updates the edu timeline item with the given id
 * @param id the id of the edu timeline item
 * @param e the event that triggered the function
 */
function updateEduItem(id, e)
{
    e.preventDefault();
    let data = {}
    data["dateFrom"] = document.querySelector(`#dateFrom${id}e`).value;
    data["dateTo"] = document.querySelector(`#dateTo${id}e`).value;
    data["grade"] = document.querySelector(`#grade${id}e`).value;
    data["course"] = document.querySelector(`#course${id}e`).value;
    
    fetch("/api/timelineData/edu/" + id, {
        method: "PATCH",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + localStorage.getItem("token")
        }
    }).then(res =>
    {
        if (res.ok)
        {
            document.querySelector(`#timelineHeader${id}e`).innerHTML = new Date(document.querySelector(`#dateFrom${id}e`).value).toLocaleString('en-gb', dateOptions) + " - " + new Date(document.querySelector(`#dateTo${id}e`).value).toLocaleString('en-gb', dateOptions);
            document.querySelector(`#timelineItem${id}e`).classList.toggle("editing");
            document.querySelector(`#grade${id}e`).setAttribute("disabled", "");
            document.querySelector(`#course${id}e`).setAttribute("disabled", "");
            return;
        }

        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }        
        
        res.json().then(json =>
        {
            document.querySelector(`#eduError${id}e`).classList.remove("hidden");
            document.querySelector(`#eduError${id}e div`).innerHTML = json.error;
        });
        
    })
}

/**
 * Updates the work timeline item with the given id
 * @param id the id of the work timeline item
 * @param e the event that triggered the function
 */
function updateWorkItem(id, e)
{
    e.preventDefault();
    let data = {}
    data["dateFrom"] = document.querySelector(`#dateFrom${id}w`).value;
    data["dateTo"] = document.querySelector(`#dateTo${id}w`).value;
    data["companyName"] = document.querySelector(`#companyName${id}w`).value;
    data["area"] = document.querySelector(`#area${id}w`).value;
    data["title"] = document.querySelector(`#jobTitle${id}w`).value;
    
    fetch("/api/timelineData/work/" + id, {
        method: "PATCH",
        body: JSON.stringify(data),
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + localStorage.getItem("token")
        }
    }).then(res => 
    {
        if(res.ok)
        {
            document.querySelector(`#timelineHeader${id}w`).innerHTML = new Date(document.querySelector(`#dateFrom${id}w`).value).toLocaleString('en-gb', dateOptions) + " - " + new Date(document.querySelector(`#dateTo${id}w`).value).toLocaleString('en-gb', dateOptions);
            document.querySelector(`#timelineItem${id}w`).classList.toggle("editing");
            document.querySelector(`#companyName${id}w`).setAttribute("disabled", "");
            document.querySelector(`#area${id}w`).setAttribute("disabled", "");
            document.querySelector(`#jobTitle${id}w`).setAttribute("disabled", "");
            return;
        }
        
        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }
        
        res.json().then(json =>
        {
            document.querySelector(`#workError${id}w`).classList.remove("hidden");
            document.querySelector(`#workError${id}w div`).innerHTML = json.error;
        });
    });
}

/**
 * Deletes the timeline item with the given id
 * @param id the id of the timeline item
 */
function deleteEduItem(id)
{
    fetch("/api/timelineData/edu/" + id, {
        method: "DELETE",
        headers: {
            "Authorization": "Bearer " + localStorage.getItem("token")
        }
    }).then(res => 
    {
        if (res.ok)
        {
            document.querySelector(`#timelineItem${id}e`).remove();
            return;
        }

        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }
        res.json().then(json => alert(json.error));
    });
}

/**
 * Updates the timeline item with the given id
 * @param id the id of the timeline item
 */
function deleteWorkItem(id)
{
    fetch("/api/timelineData/work/" + id, {
        method: "DELETE",
        headers: {
            "Authorization": "Bearer " + localStorage.getItem("token")
        }
    }).then(res =>
    {
        if (res.ok)
        {
            document.querySelector(`#timelineItem${id}w`).remove();
            return;
        }

        if (res.status === 401)
        {
            window.location.href = "./";
            return;
        }
        res.json().then(json => alert(json.error));

    }); 
}