<template>
    <div
        v-if="view === 'open'"
        class="tb-hours-simple__open"
    />
    <div
        v-else-if="view === 'closed'"
        class="tb-hours-simple__closed"
    >
        <svg
            class="c-icon tb-hours-simple__closed-icon"
            role="img"
        >
            <use xlink:href="#icon-close" />
        </svg>
    </div>
</template>
<script>
import formatDate from 'date-fns/format';
import  { DayBreak } from '@nimius/toubiz-opening-times-calculation';
import { hasLanguageLabels } from './has-language-label.mixin';

const VIEW = Object.freeze({
    NONE: 'none',
    OPEN: 'open',
    CLOSED: 'closed',
});


export default {
    name: 'TbOpeningTimesLinePreview',
    mixins: [ hasLanguageLabels ],
    props: {
        openingTimes: { type: Object, required: true },
        dateFormat: { type: String, default: 'YYYY-MM-DD' },
        forDateAndTime: { type: Date, default: () => new Date() },
    },

    data: () => ({
        nextOpenDate: null,
        resolvedOpeningTimes: null,
    }),

    watch: {
        openingTimes: {
            handler: 'updateResolvedOpeningTimes',
            immediate: true,
        },
        forDateAndTime: 'updateResolvedOpeningTimes',
    },

    methods: {
        updateResolvedOpeningTimes() {
            const resolvedOpeningTimes = this.openingTimes.timesAt(this.forDateAndTime);
            this.resolvedOpeningTimes = DayBreak.
                updateEndTimeOfSingleTimesAtResultIfSpillingOverToNextDay(resolvedOpeningTimes);
            const nextOpen = new Date(this.resolvedOpeningTimes.nextOpenDate);
            this.resolvedOpeningTimes.nextOpenWeekday = nextOpen.getDay();
            this.nextOpenDate = formatDate(nextOpen, this.dateFormat);
        },
    },

    computed: {
        view() {
            const openingTimes = this.resolvedOpeningTimes;

            if (
                !openingTimes ||
                (!openingTimes.isOpen && !openingTimes.nextOpenDate)
            ) {
                return VIEW.NONE;
            }

            if (openingTimes.openingTimes?.isAlwaysOpen) {
                return VIEW.OPEN;
            }

            if (openingTimes.isOpen) {
                return VIEW.OPEN;
            }

            return VIEW.CLOSED;
        },
    },
};
</script>
