<script>
import { getSchedule } from '@/api/calendar'
import { getSchedule as getScheduleCache } from '@/utils/cache'
import { ScheduleType } from '@/constant'
import ScheduleCalendar from './ScheduleCalendar'
import ScheduleSwiper from './ScheduleSwiper'

export default {
  name: 'ScheduleComponent',
  components: {
    ScheduleCalendar,
    ScheduleSwiper
  },
  props: {
    schedule: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      options: null
    }
  },
  watch: {
    schedule: {
      handler () {
        this.getSchedule()
      },
      immediate: true
    }
  },
  methods: {
    getApi () {
      return this.$attrs.editable ? getSchedule : getScheduleCache
    },
    getSchedule () {
      const options = {
        loading: true,
        error: false,
        detail: null
      }
      this.options = options
      this.getApi()(this.schedule).then(
        schedule => {
          options.detail = schedule
        },
        () => {
          options.error = true
        }
      ).finally(() => {
        options.loading = false
      })
    }
  },
  render (h) {
    if (this.options.loading) {
      return h('div', {
        class: 'c-schedule',
        directives: [
          {
            name: 'loading',
            value: true
          }
        ]
      })
    }

    if (this.options.error) {
      return h('StatusWrapper', {
        props: {
          error: true
        },
        on: {
          retry: this.getSchedule
        }
      })
    }

    const { detail } = this.options
    return h(detail.type === ScheduleType.RECUR ? 'ScheduleSwiper' : 'ScheduleCalendar', {
      props: {
        detail,
        ...this.$attrs
      },
      on: this.$listeners
    })
  }
}
</script>

<style lang="scss" scoped>
.c-schedule {
  min-height: 300px;
}
</style>
