<template>
  <ui-select
    v-model="localValue"
    :options="items"
    :class="themeClasses"
    v-bind="$attrs"
    class="mm-time-select">
    <slot></slot>
  </ui-select>
</template>

<script>
import Select from "../select"
import input from "../../mixins/input"
import themeSelect from "../../mixins/theme-select"
import config from "../../managers/config"

config.defaults({
  "TimeSelect.start": "09:00",
  "TimeSelect.end": "18:00",
  "TimeSelect.step": "00:30",
})

const timeParser = function(time = "") {
  const temp = time.split(":")

  return temp.length >= 2
    ? {
      hour: parseInt(temp[0]),
      minute: parseInt(temp[1]),
    }
    : null
}

const compareTime = function(time1, time2) {
  const minutes1 = time1.hour * 60 + time1.minute
  const minutes2 = time2.hour * 60 + time2.minute

  return minutes1 === minutes2 ? 0 : minutes1 < minutes2 ? -1 : 1
}

const formatTime = function(time) {
  return `0${time.hour}`.slice(-2) + ":" + `0${time.minute}`.slice(-2)
}

const getNextTime = function(time, step) {
  let hour = time.hour + step.hour
  let minute = time.minute + step.minute

  hour = hour + Math.floor(minute / 60)
  minute = minute % 60

  return {
    hour,
    minute,
  }
}

export default {
  name: "mm-time-select",
  components: {
    "ui-select": Select,
  },
  mixins: [input, themeSelect],
  inheritAttrs: false,
  props: {
    value: {
      type: String,
    },
    start: {
      type: String,
      default: () => config.get("TimeSelect.start"),
    },
    end: {
      type: String,
      default: () => config.get("TimeSelect.end"),
    },
    step: {
      type: String,
      default: () => config.get("TimeSelect.step"),
    },
    disabledTime: {
      type: Function,
      default() {
        return false
      },
    },
  },
  data() {
    return {
      localValue: "",
    }
  },
  computed: {
    items() {
      const start = timeParser(this.start)
      const end = timeParser(this.end)
      const step = timeParser(this.step)

      let list = []
      let current = start

      while (compareTime(current, end) === -1) {
        list.push({
          label: formatTime(current),
          value: formatTime(current),
          disabled: this.disabledTime(current),
        })

        current = getNextTime(current, step)
      }

      return list
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(value) {
        this.localValue = value
      }
    },
    localValue(value) {
      this.$emit("input", value)
    },
  },
}
</script>
