import { ICalCalendar, ICalCalendarMethod } from 'ical-generator';

export default class ProgramIcal {
  getDate(date, time) {
    const d = new Date(date);
    const [ hours, mins ] = time.split(":");
    d.setHours(hours);
    d.setMinutes(mins);
    return d
  }

  getLocalized(item, lang) {
    if (typeof item === "string") return item;
    return item[lang];
  }

  data() {
    return {
      permalink: data => `/${data.lang}/program.ics`
    }
  }

  render({ ese, program, lang }) {
    const url = `https://ese.ifsr.de/${ese.year}`;

    const cal = new ICalCalendar({
      name: `ESE ${ese.year}`,
      url,
      method: ICalCalendarMethod.PUBLISH,
    });

    for (const [date, events] of Object.entries(program)) {
      for (const [i, event] of events.entries()) {
        // nunjucks loops are 1-indexed by default
        const id = `${date}_${i+1}`;

        let description = this.getLocalized(event.description, lang);

        if ("annotation" in event && event.annotation !== null) {
          description += "\n\n";
            + (lang == "en" ? "Notice: " : "Hinweis: ")
            + this.getLocalized(event.annotation, lang);
        }

        if ("location" in event && event.location !== null) {
          description += "\n\n"
            + (lang == "en" ? "Location: " : "Veranstaltungsort: ")
            + this.getLocalized(event.location, lang);
        }

        cal.createEvent({
          id,
          start: this.getDate(date, event.start),
          end: ("end" in event && event.end !== null)
            ? this.getDate(date, event.end)
            : this.getDate(date, "23:59"),
          summary: this.getLocalized(event.title, lang),
          description,
          url: `${url}/${lang}/program/#${id}`,
        });
      }
    }

    return cal.toString()
  }
}
