import { calendarStatus } from "@/constants/calendar-status";
import { getDateFormat } from "@/helpers/date-helper";
export function getCalendarFile(calFile) {
    const dateFormat = "yyyyMMddTHHmmss";
    var calEvent = [];
    calEvent.push("BEGIN:VCALENDAR");
    calEvent.push("VERSION:2.0");
    calEvent.push("BEGIN:VEVENT");
    calEvent.push("DTSTAMP:" + calFile.TimeStamp);
    calEvent.push("UID:" + calFile.UniqueId + "@safelite.com");
    calEvent.push("PRODID:noreply@safelite.com");
    switch (calFile.Status) {
        case calendarStatus.BUSY:
            calEvent.push("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
            break;
        case calendarStatus.FREE:
            calEvent.push("TRANSP:TRANSPARENT");
            break;
        case calendarStatus.TENTATIVE:
            calEvent.push("STATUS:TENTATIVE");
            break;
        case calendarStatus.OUT_OF_THE_OFFICE:
            calEvent.push("X-MICROSOFT-CDO-BUSYSTATUS:OOF");
            break;
        default:
        //throw new Exception("Invalid CalendarStatus");
    }
    if (calFile.AllDayEvent) {
        calEvent.push("DTSTART;VALUE=DATE:" + getDateFormat(calFile.StartDate, dateFormat));
        calEvent.push("DTEND;;VALUE=DATE:" + getDateFormat(calFile.EndDate, dateFormat));
    } else {
        calEvent.push("DTSTART:" + getDateFormat(calFile.StartDate, dateFormat));
        calEvent.push("DTEND:" + getDateFormat(calFile.EndDate, dateFormat));
    }

    calEvent.push("SUMMARY:" + ToCalendarFileString(calFile.Subject, " "));
    if (calFile.Location != null && calFile.Location != "") {
        calEvent.push("LOCATION:" + ToCalendarFileString(calFile.Location, " "));
    }
    if (calFile.Body != null && calFile.Body != "") {
        if (calFile.IsHTML) {
            calEvent.push("DESCRIPTION:" + ToCalendarFileString(calFile.Body));
            calEvent.push(
                "X-ALT-DESC;FMTTYPE=text/html:" +
                    '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">' +
                    "<HTML><HEAD><TITLE></TITLE></HEAD><BODY>" +
                    '<P DIR=LTR><SPAN LANG="en-us">' +
                    "</SPAN>" +
                    ToCalendarFileString(calFile.Body) +
                    "</BODY></HTML>"
            );
        } else {
            calEvent.push("DESCRIPTION:" + ToCalendarFileString(calFile.Body));
        }
    }
    calEvent.push("END:VEVENT");
    calEvent.push("END:VCALENDAR");
    return calEvent.join("\r\n");
}

function ToCalendarFileString(str, replacementArg = "<p>") {
    return str.replace("\r\n", replacementArg);
}

export function download(filename, fileBody) {
    var element = document.createElement("a");
    element.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(fileBody));
    element.setAttribute("download", filename);

    element.style.display = "none";
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
}
