<template>
    <div>
        <b-modal
            ref="modalEmissionManagerCreate"
            :title="$t('scheduleEditor.titleCreate', { show: selectedShow.name })"
            :cancel-title="$t('cancel')"
            size="lg"
            @ok="create"
        >
            <b-alert
                variant="warning"
                :show="pastEventWarning"
            >
                <span v-html="$t('scheduleEditor.pastEventWarning')" />
            </b-alert>

            <div v-if="loaded.modal && !submitting">
                <b-row>
                    <b-col cols="12">
                        <label class="tw-w-full tw-font-bold">
                            <span class="tw-inline-block tw-pb-2">{{ $t('rrule.rrule') }}</span>
                            <b-form-select
                                v-model="valuePick.rrule"
                                :options="rruleOptions"
                            />
                        </label>
                    </b-col>
                </b-row>

                <b-row>
                    <b-col cols="3">
                        <label class="tw-w-full tw-font-bold">
                            <span class="tw-inline-block tw-pb-2">{{ $t('scheduleEditor.fromDate' ) }}</span>
                            <b-form-input
                                v-model="valuePick.dstart"
                                type="date"
                            />
                        </label>
                    </b-col>
                    <b-col
                        v-if="valuePick.rrule !== 1"
                        cols="3"
                    >
                        <label class="tw-w-full tw-font-bold">
                            <span
                                class="tw-inline-block tw-pb-2"
                                v-html="$t('scheduleEditor.toDate')"
                            />
                            <b-form-input
                                v-model="valuePick.until"
                                type="date"
                            />
                        </label>
                    </b-col>
                    <b-col cols="3">
                        <label class="tw-w-full tw-font-bold">
                            <span class="tw-inline-block tw-pb-2">{{ $t('scheduleEditor.from') }}</span>
                            <b-form-input
                                v-model="valuePick.tstart"
                                type="time"
                            />
                        </label>
                    </b-col>
                    <b-col cols="3">
                        <label class="tw-w-full tw-font-bold">
                            <span class="tw-inline-block tw-pb-2">{{ $t('scheduleEditor.to') }}</span>
                            <b-form-input
                                v-model="valuePick.tend"
                                type="time"
                            />
                        </label>
                    </b-col>
                </b-row>
            </div>
            <div v-else>
                <b-row>
                    <b-col align="center">
                        <img
                            src="/assets/radio.gif"
                            :alt="$t('loading')"
                        >
                    </b-col>
                </b-row>
            </div>

            <template #modal-footer="{ ok, cancel }">
                <div class="tw-flex tw-justify-between tw-items-center tw-w-full">
                    <span v-html="$t('scheduleEditor.projectedDuration', { duration: projectedTimeslotDuration })" />

                    <div class="tw-space-x-2">
                        <b-button @click="cancel()">
                            {{ $t('cancel') }}
                        </b-button>
                        <b-button
                            variant="primary"
                            @click="ok()"
                        >
                            OK
                        </b-button>
                    </div>
                </div>
            </template>
        </b-modal>
    </div>
</template>

<script>
    import {mapGetters} from 'vuex'
    import prettyDate from '../../mixins/prettyDate'
    import rrules from '../../mixins/rrules'

    export default {
        mixins: [prettyDate, rrules],

        data() {
            return {
                newSchedule: null,
                loadedModal: false,
                submitting: false,
                pastEventWarning: false,
                valuePick: {
                    dstart: null,
                    tstart: null,
                    dend: null,
                    tend: null,
                    until: null,
                    rrule: 1
                },
            }
        },

        computed: {
            loaded() {
                return {
                    shows: this.$store.state.shows.loaded['shows'],
                    modal: this.loadedModal,
                }
            },

            projectedTimeslotDuration() {
                const {dstart, tstart, dend, tend} = this.valuePick

                const d1 = new Date(`${dstart} ${tstart}`)
                const d2 = new Date(`${dend} ${tend}`)

                const diffInNs = (d2 - d1) * 1000 * 1000
                const diffInMinutes = this.nanosecondsToMinutes(diffInNs)

                return this.minutesToHm(diffInMinutes)
            },

            ...mapGetters({
                selectedShow: 'shows/selectedShow',
            })
        },

        methods: {
            create(event) {
                // prevent the modal from closing automatically on click
                event.preventDefault()
                // check for past dates; as past dates will be ignored by steering we
                // want to make the user aware - otherwise it might get confusing in
                // conflict resolution
                let now = this.apiDate(new Date())
                if (this.valuePick.dstart < now) {
                    this.valuePick.dstart = now
                    this.pastEventWarning = true
                    return
                } else {
                    this.pastEventWarning = false
                }
                // take all values that have been picked and put them into our new
                // schedule. so far we do not need any transformations.
                this.newSchedule.schedule.dstart = this.valuePick.dstart
                this.newSchedule.schedule.tstart = this.valuePick.tstart
                this.newSchedule.schedule.tend = this.valuePick.tend
                this.newSchedule.schedule.until = this.valuePick.until
                this.newSchedule.schedule.rrule = this.valuePick.rrule
                this.newSchedule.schedule.byweekday = this.getWeekdayFromApiDate(this.valuePick.dstart)

                // ok then, let's submit and see if any conflicts arise
                this.submitting = true
                this.$store.dispatch('shows/submitSchedule', {
                    showId: this.selectedShow.id,
                    schedule: this.newSchedule,
                    callback: (response) => {
                        // we have to check if there are any conflicts with existing timeslots
                        let conflicts = false
                        for (let i in response.data.projected) {
                            if (response.data.projected[i].collisions.length > 0) {
                                conflicts = true
                                break
                            }
                        }
                        // if there are no conflicts we can set an empty solutions object
                        // in our newSchedule and submit it.
                        if (!conflicts) {
                            this.newSchedule.solutions = {}
                            this.submit()
                            // otherwise we have to resolve the conflict first.
                        } else {
                            this.submitting = false
                            this.$parent.resolve(response.data)
                            this.$refs.modalEmissionManagerCreate.hide()
                        }
                    },
                    callbackCancel: () => {
                        this.submitting = false
                    }
                })
            },

            submit() {
                this.$store.dispatch('shows/submitSchedule', {
                    showId: this.selectedShow.id,
                    schedule: this.newSchedule,
                    callback: (response) => {
                        this.submitting = false
                        // if for some reason a new conflict arose, e.g. because in the meantime
                        // someone else inserted a conflicting schedule, we have to resolve.
                        // TODO: based on single event schedule
                        // TODO: check for complex schedules with resolved conflicts
                        if (response.data.projected === undefined) {
                            this.$parent.renderView(null)
                        } else {
                            this.$log.debug('Timeslot conflict. Switching to resolve mode.')
                            this.$parent.resolve(response.data)
                        }
                        this.$refs.modalEmissionManagerCreate.hide()
                    },
                    callbackCancel: () => {
                        this.submitting = false
                    }
                })
            },

            // initialise a new schedule and open the modal
            open(start, end) {
                let dstart = start.format('YYYY-MM-DD')
                let tstart = start.format('HH:mm')
                let dend = end.format('YYYY-MM-DD')
                let tend = end.format('HH:mm')
                let until = end.format('YYYY-MM-DD')
                let now = this.apiDate(new Date())
                if (dstart < now) {
                    dstart = now
                    this.pastEventWarning = true
                } else {
                    this.pastEventWarning = false
                }
                this.valuePick.dstart = dstart
                this.valuePick.tstart = tstart
                this.valuePick.dend = dend
                this.valuePick.tend = tend
                this.valuePick.until = until
                this.newSchedule = {
                    schedule: {
                        rrule: 1,
                        show: 0,
                        byweekday: 0,
                        dstart: dstart,
                        tstart: tstart,
                        tend: tend,
                        until: until,
                        is_repetition: false,
                        add_days_no: 0,
                        add_business_days_only: false,
                        default_playlist_id: 0,
                        automation_id: 0,
                    }
                }
                this.loadedModal = true
                this.submitting = false
                this.$refs.modalEmissionManagerCreate.show()
            },
        }
    }
</script>

<style scoped>
    .row {
        margin-bottom: 1em;
    }
</style>