<template>
    <div>
        <slot
                :isOpen="isOpen"
                :timeRange="timeRange"
                :resolvedOpeningTimes="resolvedOpeningTimes"
                :openingTimes="openingTimes"
                :upcomingOpeningTimes="upcomingOpeningTimes"
        />
    </div>
</template>

<script>
import { ToubizLegacyParser } from '@nimius/toubiz-opening-times-calculation';

const parsers = {
    legacy: ToubizLegacyParser,
};

export default {
    name: 'TbOpeningTimesParser',

    props: {
        openingTimesDefinition: {
            type: Object,
            required: true,
        },
        openingTimesFormat: {
            type: String,
            required: true,
            validator(value) {
                if (Object.keys(parsers).indexOf(value) === -1) {
                    console.warn(`openingTimesFormat must be one of ${Object.keys(parsers).join(', ')}. ${value} is not allowed.`);
                    return false;
                }
                return true;
            }
        },
    },

    methods: {

        getNextDates(numberOfDays) {
            const dates = [];
            for (let i = 0; i < numberOfDays; i++) {
                const date = new Date();
                date.setDate(date.getDate() + i);
                dates.push(date);
            }
            return dates;
        }
    },

    computed: {
        upcomingOpeningTimes() {
            const upcoming = [];
            for (const date of this.getNextDates(7)) {
                upcoming.push({
                    weekday: date.getDay(),
                    times: this.openingTimes ? this.openingTimes.openingTimesForDate(date) : null,
                })
            }
            return upcoming;
        },

        isOpen() {
            if (!this.resolvedOpeningTimes) {
                return false;
            }

            return this.resolvedOpeningTimes.isOpen;
        },

        timeRange() {
            if (!this.resolvedOpeningTimes) {
                return null;
            }

            return this.resolvedOpeningTimes.timeRange;
        },

        resolvedOpeningTimes() {
            if (!this.openingTimes) {
                return null;
            }

            return this.openingTimes.timesAt(new Date());
        },

        /**
         * @returns {OpeningTimesCollection|null}
         */
        openingTimes() {
            if (!this.openingTimesDefinition) {
                return null;
            }

            const Constructor = parsers[this.openingTimesFormat];
            const collection = (new Constructor()).parse(this.openingTimesDefinition);
            if (!collection || collection.times.length === 0) {
                return null;
            }
            return collection;
        }
    }
}
</script>