<template>
  <div>
    <h2 class="chill-red">
      {{ $t("choose_your_calendar_user") }}
    </h2>
    <VueMultiselect
      name="field"
      id="calendarUserSelector"
      v-model="value"
      track-by="id"
      label="value"
      :custom-label="transName"
      :placeholder="$t('select_user')"
      :multiple="true"
      :close-on-select="false"
      :allow-empty="true"
      :model-value="value"
      :select-label="$t('multiselect.select_label')"
      :deselect-label="$t('multiselect.deselect_label')"
      :selected-label="$t('multiselect.selected_label')"
      @select="selectUsers"
      @remove="unSelectUsers"
      @close="coloriseSelectedValues"
      :options="options"
    />
  </div>
  <div class="form-check">
    <input
      type="checkbox"
      id="myCalendar"
      class="form-check-input"
      v-model="showMyCalendarWidget"
    />
    <label class="form-check-label" for="myCalendar">{{
      $t("show_my_calendar")
    }}</label>
  </div>
  <div class="form-check">
    <input
      type="checkbox"
      id="weekends"
      class="form-check-input"
      @click="toggleWeekends"
    />
    <label class="form-check-label" for="weekends">{{
      $t("show_weekends")
    }}</label>
  </div>
</template>
<script>
import { fetchCalendarRanges, fetchCalendar } from "../../_api/api";
import VueMultiselect from "vue-multiselect";
import { whoami } from "ChillPersonAssets/vuejs/AccompanyingCourse/api";

const COLORS = [
  /* from https://colorbrewer2.org/#type=qualitative&scheme=Set3&n=12 */
  "#8dd3c7",
  "#ffffb3",
  "#bebada",
  "#fb8072",
  "#80b1d3",
  "#fdb462",
  "#b3de69",
  "#fccde5",
  "#d9d9d9",
  "#bc80bd",
  "#ccebc5",
  "#ffed6f",
];

export default {
  name: "CalendarUserSelector",
  components: { VueMultiselect },
  props: [
    "users",
    "updateEventsSource",
    "calendarEvents",
    "showMyCalendar",
    "toggleMyCalendar",
    "toggleWeekends",
  ],
  data() {
    return {
      errorMsg: [],
      value: [],
      options: [],
    };
  },
  computed: {
    showMyCalendarWidget: {
      set(value) {
        this.toggleMyCalendar(value);
        this.updateEventsSource();
      },
      get() {
        return this.showMyCalendar;
      },
    },
  },
  methods: {
    init() {
      this.fetchData();
    },
    fetchData() {
      fetchCalendarRanges()
        .then(
          (calendarRanges) =>
            new Promise((resolve, reject) => {
              let results = calendarRanges.results;

              let users = [];

              results.forEach((i) => {
                if (!users.some((j) => i.user.id === j.id)) {
                  let ratio = Math.floor(users.length / COLORS.length);
                  let colorIndex = users.length - ratio * COLORS.length;
                  users.push({
                    id: i.user.id,
                    username: i.user.username,
                    color: COLORS[colorIndex],
                  });
                }
              });

              let calendarEvents = [];
              users.forEach((u) => {
                let arr = results
                  .filter((i) => i.user.id === u.id)
                  .map((i) => ({
                    start: i.startDate.datetime,
                    end: i.endDate.datetime,
                    calendarRangeId: i.id,
                    sourceColor: u.color,
                    //display: 'background' // can be an option for the disponibility
                  }));
                calendarEvents.push({
                  events: arr,
                  color: u.color,
                  textColor: "#444444",
                  editable: false,
                  id: u.id,
                });
              });

              this.users.loaded = users;
              this.options = users;

              this.calendarEvents.loaded = calendarEvents;
              whoami().then(
                (me) =>
                  new Promise((resolve, reject) => {
                    this.users.logged = me;
                    let currentUser = users.find((u) => u.id === me.id);
                    this.value = currentUser;

                    fetchCalendar(currentUser.id).then(
                      (calendar) =>
                        new Promise((resolve, reject) => {
                          let results = calendar.results;
                          let events = results.map((i) => ({
                            start: i.startDate.datetime,
                            end: i.endDate.datetime,
                          }));
                          let calendarEventsCurrentUser = {
                            events: events,
                            color: "darkblue",
                            id: 1000,
                            editable: false,
                          };
                          this.calendarEvents.user = calendarEventsCurrentUser;

                          this.selectUsers(currentUser);

                          resolve();
                        }),
                    );

                    resolve();
                  }),
              );

              resolve();
            }),
        )
        .catch((error) => {
          this.errorMsg.push(error.message);
        });
    },
    transName(value) {
      return `${value.username}`;
    },
    coloriseSelectedValues() {
      let tags = document.querySelectorAll("div.multiselect__tags-wrap")[0];

      if (tags.hasChildNodes()) {
        let children = tags.childNodes;
        for (let i = 0; i < children.length; i++) {
          let child = children[i];
          if (child.nodeType === Node.ELEMENT_NODE) {
            this.users.selected.forEach((u) => {
              if (child.hasChildNodes()) {
                if (child.firstChild.innerText == u.username) {
                  child.style.background = u.color;
                  child.firstChild.style.color = "#444444";
                }
              }
            });
          }
        }
      }
    },
    selectEvents() {
      let selectedUsersId = this.users.selected.map((a) => a.id);
      this.calendarEvents.selected = this.calendarEvents.loaded.filter((a) =>
        selectedUsersId.includes(a.id),
      );
    },
    selectUsers(value) {
      this.users.selected.push(value);
      this.coloriseSelectedValues();
      this.selectEvents();
      this.updateEventsSource();
    },
    unSelectUsers(value) {
      this.users.selected = this.users.selected.filter((a) => a.id != value.id);
      this.selectEvents();
      this.updateEventsSource();
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style src="vue-multiselect/dist/vue-multiselect.css"></style>
