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


const parsers = {
    'legacy': ToubizLegacyParser,
    'legacy-attraction': ToubizLegacyAttractionParser,
    'toubizV1': ToubizV1Parser,
};

function validateOpeningTimesType(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;
}

/**
 * Wrapper component that provides the opening times parsing functionality in a convinient form.
 * This component does not render any markup itself: It only takes opening times definitions and
 * passes the parsed opening times collection to the default slot.
 *
 * @example
 * <tb-opening-times-parser
 *      :opening-times-definition="article.openingTimes"
 *      :opening-times-format="article.openingTimesFormat"
 * >
 *      <template v-slot="{ openingTimes }">
 *          <pre><code>{{ openingTimes }}</code></pre>
 *      </template>
 * </tb-opening-times>
 */
export default {
    name: 'TbOpeningTimesParser',

    render() {
        if (!this.$scopedSlots.default) {
            return null;
        }

        const content = this.$scopedSlots.default({ openingTimes: this.openingTimes });
        if (!content) {
            return null;
        }

        if (content.length > 1) {
            console.warn(
                'tb-opening-times-parser must have a default slot that renders at most a single element.'
            );
        }

        return content[0] || null;
    },

    props: {
        openingTimesDefinition: {
            type: Object,
            required: true,
        },
        openingTimesFormat: {
            type: String,
            required: true,
            validator: validateOpeningTimesType,
        },
    },

    computed: {
        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>
