<script>
  const pageSize = 10;

  export default {
    props: {
      calendarId: {
        type: String,
        required: true,
      },
      apiKey: {
        type: String,
        required: true,
      }
    },
    data() {
      return {
        events: [],
        toShow: 7,
      };
    },
    computed: {
      displayedEvents() {
        return this.events.slice(0, this.toShow);
      },
      hasMore() {
        return this.toShow < this.events.length;
      },
    },
    methods: {
      onShowMore() {
        this.toShow += pageSize;
      },
      loadEventsFromStorage() {
        if (window.sessionStorage && window.sessionStorage['__pircal_' + this.calendarId]) {
          return JSON.parse(window.sessionStorage['__pircal_' + this.calendarId]);
        }
      },

      // Store events to sessionStorage if possible to save requests.
      storeEventsToStorage() {
        if (window.sessionStorage) {
          window.sessionStorage['__pircal_' + this.calendarId] = JSON.stringify(this.events);
        }
      }
    },
    mounted() {
      const ev = this.loadEventsFromStorage();

      if (! ev) {
        const toIso = now => now.toISOString().split('.')[0]+"Z";
        const now = new Date();
        const timeMin = now.toISOString();
        const timeMax = new Date(+now + (1000 * 60 * 60 * 24 * 90)).toISOString(); // 90 days ahead
        const reqUrl = `https://www.googleapis.com/calendar/v3/calendars/${this.calendarId}/events?key=${encodeURIComponent(this.apiKey)}&maxResults=150&timeMin=${encodeURIComponent(timeMin)}&timeMax=${encodeURIComponent(timeMax)}&sanitizeHtml=true&singleEvents=true&maxAtendees=1`;

        let counter = 0;

        fetch(reqUrl)
          .then(response => {
            if (!response.ok) {
              throw new Error("Problem loading events from google");
            }
            return response.json()
          })
          .then(resp => {
            this.events = resp.items
              .map(e => {
                const start = new Date(e.start.dateTime || e.start.date);
                const end = new Date(e.end.dateTime || e.end.date);

                const startDateVerbose = start.toLocaleDateString('cs-CZ', {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'});
                const startTimeVerbose = start.getHours() + ':' + start.getMinutes().toString().padStart(2, '0');

                const allDay = ! e.start.dateTime;

                return {
                  id: counter++,
                  start: start,
                  startTimestamp: start.getTime(),
                  startDateVerbose,
                  startTimeVerbose,
                  allDay,
                  end: end,
                  title: e.summary,
                  description: e.description,
                  link: e.htmlLink
                };
              })
              .sort((e1, e2) => e1.start < e2.start ? -1 : 1);

            this.storeEventsToStorage();
        });
      } else {
        this.events = ev;
      }
    },
    render() {
      return this.$scopedSlots.default({
        events: this.displayedEvents,
        hasMore: this.hasMore,
        onShowMore: this.onShowMore,
      });
    }
  };
</script>
