import { h } from "@stencil/core";
import { DatePickerService } from './date-picker.service';
import { getValidator } from '../../validators/validatorFactory';
import Tunnel from '../locale/i18n.provider';
let inputId = 0;
export class DatePicker {
    constructor() {
        this.calendarListener = ({ detail }) => this.handleCalendarSelection(detail);
        this.inputBlurListener = (e) => this.handleBlur(e);
        this.inputKeyListener = (e) => this.handleInputKey(e);
        this.toggleClickListener = () => this.open();
        this.overlayListener = () => this.close();
        /**
         * The date picker id
         */
        this.inputId = `'anj-date-picker-${inputId++}`;
        /**
         * How to align the overlay when it opens.
         * Options are `"bottom-end"` or `"bottom-start"` which is the default.
         */
        this.placement = 'bottom-end';
    }
    get date() {
        const date = (this.innerDateValue) ? new Date(this.innerDateValue) : new Date();
        return this.adapter.getCalendarDate(date, this.rangeParams);
    }
    injectedPropWatcher() {
        this.assignAdapter();
    }
    connectedCallback() {
        this.assignAdapter();
        this.input = this.element.parentElement;
        this.input.addEventListener('anjInput', this.inputKeyListener);
        this.input.addEventListener('anjBlur', this.inputBlurListener);
        this.connectToggle(this.input.querySelector('anj-date-picker-toggle'));
        this.configureValidationParameters();
    }
    componentDidLoad() {
        this.anjInputControlDidLoad.emit();
    }
    disconnectedCallback() {
        this.unbindCalendar();
        if (this.overlay) {
            this.overlay.removeEventListener('anjWillDismiss', this.overlayListener);
            this.overlay = null;
        }
        if (this.input) {
            this.input.removeEventListener('anjInput', this.inputKeyListener);
            this.input.removeEventListener('anjBlur', this.inputBlurListener);
        }
        const toggle = this.input.querySelector('anj-date-picker-toggle');
        if (toggle) {
            toggle.removeEventListener('click', this.toggleClickListener);
        }
    }
    /**
     * open the date picker
     */
    async open() {
        if (this.calendar)
            return;
        if (!this.overlay) {
            this.bindOverlay(this.element.querySelector('anj-overlay'));
        }
        this.bindCalendar();
        const popper = await this.overlay.popper();
        const d = this.innerDateValue || this.input.value;
        if (!popper) {
            this.configureValidationParameters();
            this.processInputValue(d ? d : '');
            this.calendar.monthMode = true;
            this.calendar.date = this.date;
            this.calendar.rangeParams = this.rangeParams;
            await this.overlay.open(this.element);
        }
        this.previouslyActiveElement = this.input.querySelector('anj-date-picker-toggle button');
        return this.calendar.focusControls();
    }
    /**
     * close the date picker
     */
    async close() {
        if (this.previouslyActiveElement) {
            await this.input.setFocus();
            this.previouslyActiveElement.focus();
            this.previouslyActiveElement = undefined;
        }
        await this.overlay.close();
        this.unbindCalendar();
    }
    /**
     * handle changes from the anj-input
     */
    processInputValue(inputValue) {
        this.innerDateValue = this.adapter.processDateInput(inputValue);
        this.outerValue = this.adapter.prepDateStringOutput(this.innerDateValue);
        if (inputValue) {
            this.anjDateChange.emit({ inner: this.adapter.convertToDate(this.innerDateValue), outer: this.outerValue });
        }
        else {
            this.anjDateChange.emit({});
        }
    }
    /**
     * handle changes from the angular directive
     */
    async setInputValue(inputValue) {
        const inputDate = (typeof inputValue === 'string') ? this.adapter.convertToDate(this.adapter.processDateInput(inputValue)) : this.adapter.processDateInput(inputValue);
        this.outerValue = this.adapter.prepDateStringOutput(inputDate);
        this.innerDateValue = this.adapter.processDateInput(this.outerValue);
        this.anjDateChange.emit({ inner: inputValue, outer: this.outerValue, refreshOuter: true });
    }
    /**
     * formatter, passed to anj-input, which supports conversion to short-date
     */
    inputFormatter(inputValue) {
        return Promise.resolve(this.adapter.prepDateStringOutput(inputValue));
    }
    /**
     * comparator, passed to anj-input, which compares two dates of various formats for parity
     */
    hasValueChanged(newVal, oldVal) {
        return Promise.resolve(this.adapter.prepDateStringOutput(newVal) !== this.adapter.prepDateStringOutput(oldVal));
    }
    async innerValue() {
        return this.innerDateValue;
    }
    // VALIDATION BLOCK
    async remoteCustomValidator(valueString) {
        const valueDate = this.adapter.processDateInput(valueString);
        return this.updateCustomValidity(valueDate);
    }
    configureValidationParameters() {
        this.rangeParams = {};
        if (this.input.min) {
            this.min = this.adapter.processDateInput(this.input.min);
            this.rangeParams.minDate = this.min;
        }
        if (this.input.max) {
            this.max = this.adapter.processDateInput(this.input.max);
            this.rangeParams.maxDate = this.max;
        }
        this.setCustomValidator();
    }
    setCustomValidator() {
        this.validator = getValidator([
            { name: 'min', options: { min: this.min } },
            { name: 'max', options: { max: this.max } }
        ]);
    }
    updateCustomValidity(value) {
        let response = {};
        if (this.validator) {
            response = this.validator.validate(value);
        }
        return response;
    }
    assignAdapter() {
        this.adapter = new DatePickerService(this.locale, this.language, this.timezoneOverride, this.dateFormat);
    }
    connectToggle(toggle) {
        if (toggle) {
            toggle.addEventListener('click', this.toggleClickListener);
        }
    }
    handleBlur({ target }) {
        if (target.tagName === 'ANJ-INPUT') {
            this.processInputValue(target.value);
        }
    }
    handleCalendarSelection(dateSelection) {
        this.innerDateValue = dateSelection;
        this.outerValue = this.adapter.localize(this.innerDateValue);
        this.input.value = this.outerValue;
        this.anjDateChange.emit({ inner: this.adapter.convertToDate(this.innerDateValue), outer: this.outerValue, refreshOuter: true });
        this.close();
    }
    handleInputKey({ target }) {
        this.processInputValue(target.value);
        this.input.checkValidity();
    }
    bindOverlay(el) {
        if (el) {
            this.overlay = el;
            this.overlay.addEventListener('anjWillDismiss', this.overlayListener);
        }
    }
    bindCalendar() {
        this.calendar = document.createElement('anj-calendar');
        this.overlay.appendChild(this.calendar);
        this.calendar.date = this.date;
        this.calendar.adapter = this.adapter;
        this.calendar.rangeParams = this.rangeParams;
        this.calendar.addEventListener('anjCalendarDaySelect', this.calendarListener);
    }
    unbindCalendar() {
        if (this.calendar) {
            this.calendar.removeEventListener('anjCalendarDaySelect', this.calendarListener);
            this.calendar.remove();
            this.calendar = null;
        }
    }
    render() {
        return (h("anj-overlay", { class: "anj-dropdown-menu anj-date-picker-menu", placement: this.placement, trapFocus: true }));
    }
    static get is() { return "anj-date-picker"; }
    static get originalStyleUrls() { return {
        "$": ["date-picker.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["date-picker.css"]
    }; }
    static get properties() { return {
        "locale": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [{
                        "text": "Fed by anj-locale",
                        "name": "internal"
                    }],
                "text": ""
            },
            "attribute": "locale",
            "reflect": false
        },
        "language": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "language",
            "reflect": false
        },
        "timezoneOverride": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "timezone-override",
            "reflect": false
        },
        "dateFormat": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "DateFormat",
                "resolved": "\"M/d/yyyy\" | \"dd/MM/yyyy\" | \"yyyy/M/d\"",
                "references": {
                    "DateFormat": {
                        "location": "import",
                        "path": "../locale/i18n.provider"
                    }
                }
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "date-format",
            "reflect": false
        },
        "adapter": {
            "type": "any",
            "mutable": true,
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The adapter is the brains of the date-picker."
            },
            "attribute": "adapter",
            "reflect": false
        },
        "inputId": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The date picker id"
            },
            "attribute": "input-id",
            "reflect": false,
            "defaultValue": "`'anj-date-picker-${inputId++}`"
        },
        "placement": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "'bottom-start' | 'bottom-end'",
                "resolved": "\"bottom-end\" | \"bottom-start\"",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "How to align the overlay when it opens.\nOptions are `\"bottom-end\"` or `\"bottom-start\"` which is the default."
            },
            "attribute": "placement",
            "reflect": false,
            "defaultValue": "'bottom-end'"
        }
    }; }
    static get states() { return {
        "innerDateValue": {},
        "outerValue": {},
        "rangeParams": {}
    }; }
    static get events() { return [{
            "method": "anjDateChange",
            "name": "anjDateChange",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Fires when the user has selected a value"
            },
            "complexType": {
                "original": "DateChangeEvent",
                "resolved": "DateChangeEvent",
                "references": {
                    "DateChangeEvent": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                }
            }
        }, {
            "method": "anjInputControlDidLoad",
            "name": "anjInputControlDidLoad",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Fires when the control has loaded"
            },
            "complexType": {
                "original": "void",
                "resolved": "void",
                "references": {}
            }
        }]; }
    static get methods() { return {
        "open": {
            "complexType": {
                "signature": "() => Promise<void>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "open the date picker",
                "tags": []
            }
        },
        "close": {
            "complexType": {
                "signature": "() => Promise<void>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "close the date picker",
                "tags": []
            }
        },
        "setInputValue": {
            "complexType": {
                "signature": "(inputValue: any) => Promise<void>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "handle changes from the angular directive",
                "tags": []
            }
        },
        "inputFormatter": {
            "complexType": {
                "signature": "(inputValue: string) => Promise<string>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<string>"
            },
            "docs": {
                "text": "formatter, passed to anj-input, which supports conversion to short-date",
                "tags": []
            }
        },
        "hasValueChanged": {
            "complexType": {
                "signature": "(newVal: any, oldVal: any) => Promise<boolean>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }, {
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<boolean>"
            },
            "docs": {
                "text": "comparator, passed to anj-input, which compares two dates of various formats for parity",
                "tags": []
            }
        },
        "innerValue": {
            "complexType": {
                "signature": "() => Promise<any>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<any>"
            },
            "docs": {
                "text": "",
                "tags": []
            }
        },
        "remoteCustomValidator": {
            "complexType": {
                "signature": "(valueString: string | number) => Promise<ValidatorResponse>",
                "parameters": [{
                        "tags": [],
                        "text": ""
                    }],
                "references": {
                    "Promise": {
                        "location": "global"
                    },
                    "ValidatorResponse": {
                        "location": "import",
                        "path": "../../types/types"
                    }
                },
                "return": "Promise<ValidatorResponse>"
            },
            "docs": {
                "text": "",
                "tags": []
            }
        }
    }; }
    static get elementRef() { return "element"; }
    static get watchers() { return [{
            "propName": "locale",
            "methodName": "injectedPropWatcher"
        }, {
            "propName": "language",
            "methodName": "injectedPropWatcher"
        }, {
            "propName": "timezoneOverride",
            "methodName": "injectedPropWatcher"
        }, {
            "propName": "dateFormat",
            "methodName": "injectedPropWatcher"
        }]; }
}
Tunnel.injectProps(DatePicker, ['locale', 'language', 'timezoneOverride', 'dateFormat']);
