<template>
  <div class="vue-component">
    <h2>
      <a id="section-110" />
      {{ $t("startdate.change") }}
    </h2>
    <div>
      <div class="mb-3 row">
        <div class="col-sm-12 date-update">
          <input
            class="form-control"
            type="date"
            id="startDate"
            v-model="startDateInput"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { dateToISO, ISOToDatetime } from "ChillMainAssets/chill/js/date";
import { mapState } from "vuex";

export default {
  name: "StartDate",
  data() {
    return {
      lastRecordedDate: null,
    };
  },
  computed: {
    ...mapState({
      startDate: (state) =>
        dateToISO(ISOToDatetime(state.accompanyingCourse.openingDate.datetime)),
    }),
    startDateInput: {
      get() {
        return this.startDate;
      },
      set(value) {
        this.lastRecordedDate = value;

        setTimeout(() => {
          console.log("timeout finished");
          if (this.lastRecordedDate === value) {
            console.log("last recorded", this.lastRecordedDate, "value", value);
            this.$store
              .dispatch("updateStartDate", value)
              .catch(({ name, violations }) => {
                if (
                  name === "ValidationException" ||
                  name === "AccessException"
                ) {
                  violations.forEach((violation) =>
                    this.$toast.open({
                      message: violation,
                    }),
                  );
                } else {
                  this.$toast.open({
                    message: "An error occurred",
                  });
                }
              });
          }
        }, 3000);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.date-update {
  display: flex;
  justify-content: space-between;
  &-btn {
    margin-left: 1rem;
  }
}
</style>
