<template>
  <gz-dash
    icon="$ayiCalendarCheck"
    :show-more-button="false"
    :update-frequency="300000"
    :error-message="errorMessage"
    v-bind="$attrs"
    @dash-refresh="getDataFromApi()"
    v-on="$listeners"
  >
    <template slot="main">
      <v-sheet height="400">
        <v-calendar
          ref="rvwcalendar"
          color="primary"
          type="day"
          hide-header
          :now="now"
          :interval-count="intervalCount"
          :first-time="startAt"
          :events="events"
          :event-color="getEventColor"
          :locale="languageName"
          @click:event="showEvent"
        >
          <template v-slot:event="{ event, eventSummary }">
            <div>
              <!-- eslint-disable vue/no-v-html -->
              <span
                :class="event.textColor + '--text'"
                v-html="eventSummary()"
              /><v-icon v-if="!event.editable" x-small :color="event.textColor">
                $ayiLock</v-icon
              >
            </div>
          </template>
        </v-calendar>
      </v-sheet>
    </template>
  </gz-dash>
</template>
<script>
import GzDash from "./dash-base.vue";

export default {
  components: {
    GzDash
  },
  props: {
    maxListItems: { type: Number, default: 10 }
  },
  data() {
    return {
      events: [],
      errorMessage: null,
      timeZoneName: window.$gz.locale.getResolvedTimeZoneName(),
      languageName: window.$gz.locale.getResolvedLanguage(),
      hour12: window.$gz.locale.getHour12(),
      startAt: "00:00",
      intervalCount: 24,
      now: null
    };
  },

  computed: {},
  async mounted() {
    //must be called from mounted to have refs available
    await this.getDataFromApi();
  },
  methods: {
    getEventColor(event) {
      return event.color;
    },
    showEvent({ nativeEvent, event }) {
      nativeEvent.stopPropagation();

      window.$gz.eventBus.$emit("openobject", {
        type: event.type,
        id: event.id
      });
    },

    async getDataFromApi() {
      let now = new Date();

      //set now for the calendar to trigger a refresh
      //if this doesn't work then need to trigger the change event: https://vuetifyjs.com/en/api/v-calendar/#events
      this.now = now.toLocaleString("sv-SE", {
        timeZone: this.timeZoneName
      });

      //case 4198
      if (this.$refs && this.$refs.calendar) {
        this.$refs.rvwcalendar.scrollToTime({
          hour: now.getHours(),
          minute: 0
        });
      }

      try {
        this.errorMessage = null;
        const now = window.$gz.locale.nowUTC8601String(this.timeZoneName);
        const res = await window.$gz.api.post("schedule/personal", {
          view: 1,
          dark: this.$store.state.darkMode,
          start: window.$gz.locale.addDurationToUTC8601String(now, {
            hours: -24
          }),
          end: window.$gz.locale.addDurationToUTC8601String(now, { hours: 24 }),
          wisu: false,
          reviews: true,
          reminders: false
        });
        if (res.error) {
          this.errorMessage = res.error;
        } else {
          this.events.splice(0);
          const timeZoneName = this.timeZoneName;
          let i = res.data.length;
          while (i--) {
            const x = res.data[i];
            this.events.push({
              start: new Date(
                new Date(x.start)
                  .toLocaleString("sv-SE", {
                    timeZone: timeZoneName
                  })
                  .replace(" ", "T")
              ).getTime(),
              end: new Date(
                new Date(x.end)
                  .toLocaleString("sv-SE", {
                    timeZone: timeZoneName
                  })
                  .replace(" ", "T")
              ).getTime(),
              timed: true,
              name: x.name,
              color: x.color,
              textColor: x.textColor,
              type: x.type,
              id: x.id,
              editable: x.editable,
              userId: x.userId
            });
          }
        }
      } catch (error) {
        this.errorMessage = error.toString();
      }
    }
  }
};
</script>
