import { Integration } from './integration.class';
import { template as initializeDotTemplate } from 'dot';
import { dateToShortIsoString } from '../../common/date-formatting';

/**
 * Simple integration that loads the configured URL after the user has selected a date.
 * The URL can be specified in the attribute `data-toubiz-date-picker-integration.load-page`
 * and may dot.js templates with the following placeholders:
 * - `{{=it.start}}`
 * - `{{=it.end}}`
 */
export class LoadPage extends Integration {

    /**
     * @param {HTMLElement} node
     * @returns {boolean}
     */
    static test(node) {
        return node.hasAttribute('data-toubiz-date-picker-integration.load-page');
    }

    initialize() {
        const attribute = this.node.getAttribute('data-toubiz-date-picker-integration.load-page');
        const template = initializeDotTemplate(decodeURIComponent(attribute));

        this.node.addEventListener('toubiz-date-picker.change', event => {
            window.location.href = template({
                start: dateToShortIsoString(event.detail.range.start),
                end: dateToShortIsoString(event.detail.range.end),
            });
        });
    }

}
