import { h } from "@stencil/core";
import { MeridiemTimeDisplay, MilitaryTimeDisplay, TimePickerService } from './time-picker.service';
import { getValidator } from '../../validators/validatorFactory';
import Tunnel from '../locale/i18n.provider';
let inputId = 0;
export class TimePicker {
    constructor() {
        this.clockListener = ({ detail }) => this.valueChangeHandler(detail);
        this.overlayListener = () => this.close();
        this.toggleClickListener = () => this.open();
        /**
         * The time picker id
         */
        this.inputId = `anj-time-picker-${inputId++}`;
        /**
         * Bool to display time in meridiem or military
         */
        this.meridiem = true;
        /**
         * How to align the overlay when it opens.
         * Options are `"bottom-end"` or `"bottom-start"` which is the default.
         */
        this.placement = 'bottom-end';
    }
    injectedPropWatcher() {
        this.assignStrategy();
    }
    valueHandler(newValue, oldValue) {
        if (newValue !== oldValue) {
            this.updateCustomValidity(newValue);
        }
    }
    connectedCallback() {
        this.input = this.element.parentElement;
        this.assignStrategy();
        this.connectToggle(this.input.querySelector('anj-time-picker-toggle'));
        this.setValues(this.input.value);
        this.configureValidationParameters();
    }
    componentDidLoad() {
        this.anjInputControlDidLoad.emit();
    }
    disconnectedCallback() {
        if (this.overlay) {
            this.overlay.removeEventListener('anjWillDismiss', this.overlayListener);
            this.overlay = null;
        }
        if (this.clock) {
            this.clock.removeEventListener('anjTimeChanged', this.clockListener);
            this.clock = null;
        }
        const toggle = this.input.querySelector('anj-time-picker-toggle');
        if (toggle) {
            toggle.removeEventListener('click', this.toggleClickListener);
        }
    }
    /**
     * open the time picker
     */
    async open() {
        if (!this.overlay) {
            this.bindOverlay(this.element.querySelector('anj-overlay'));
            this.bindClock(this.element.querySelector('anj-time-picker-clock'));
        }
        const popper = await this.overlay.popper();
        if (!popper) {
            this.configureValidationParameters();
            await this.overlay.open(this.element);
            setTimeout(() => this.clock.focusHour(), 100);
        }
        this.setValues(this.input.value);
    }
    /**
     * close the time picker
     */
    async close() {
        await this.overlay.close();
        this.updateInputValue();
    }
    /**
     * formatter, passed to anj-input, currently a pass-through
     */
    inputFormatter(inputValue) {
        this.input.placeholder = this.strategy.genPlaceHolder(null);
        return Promise.resolve(inputValue);
    }
    /**
     * comparator, passed to anj-input, which compares two time strings for parity
     */
    hasValueChanged(newVal, oldVal) {
        this.input.placeholder = this.strategy.genPlaceHolder(null);
        return Promise.resolve(newVal !== oldVal);
    }
    async innerValue() {
        return this.value;
    }
    async remoteCustomValidator(valueString) {
        const militaryTimeSegments = TimePickerService.parseToTimeFields(valueString)['military'];
        const valueAsNum = militaryTimeSegments.hour.concat(militaryTimeSegments.minutes);
        return this.updateCustomValidity(valueAsNum);
    }
    assignStrategy() {
        this.strategy = (this.meridiem) ? new MeridiemTimeDisplay(this.locale, this.language) : new MilitaryTimeDisplay(this.locale, this.language);
    }
    configureValidationParameters() {
        if (this.input.min) {
            const { boundary } = this.strategy.minmaxHandler(this.input.min);
            this.min = boundary;
        }
        if (this.input.max) {
            const { boundary } = this.strategy.minmaxHandler(this.input.max);
            this.max = boundary;
        }
        this.setCustomValidator();
    }
    connectToggle(toggle) {
        if (toggle) {
            toggle.addEventListener('click', this.toggleClickListener);
        }
    }
    setCustomValidator() {
        this.validator = getValidator([
            { name: 'min', options: { min: this.min } },
            { name: 'max', options: { max: this.max } }
        ]);
    }
    setValues(value) {
        if (value && value === '') {
            this.value = undefined;
        }
        else if (value) {
            this.value = value.toString();
        }
    }
    updateCustomValidity(value) {
        let response = {};
        if (this.validator) {
            response = this.validator.validate(value);
        }
        return response;
    }
    updateInputValue() {
        this.input.value = (this.value) ? this.value : '';
        this.anjClockSelection.emit(this.value);
    }
    valueChangeHandler({ parsedValue }) {
        this.input.placeholder = this.strategy.genPlaceHolder(parsedValue);
        if (parsedValue && parsedValue.hour && parsedValue.minutes) {
            this.value = this.strategy.stringifyParsedTime(parsedValue, this.timezone);
        }
    }
    bindOverlay(el) {
        if (el) {
            this.overlay = el;
            this.overlay.addEventListener('anjWillDismiss', this.overlayListener);
        }
    }
    bindClock(el) {
        if (el) {
            this.clock = el;
            this.clock.addEventListener('anjTimeChanged', this.clockListener);
        }
    }
    render() {
        const overlayClasses = this.meridiem ? 'anj-time-picker-menu anj-dropdown-menu' : 'anj-time-picker-menu anj-dropdown-menu anj-no-control';
        return (h("anj-overlay", { class: overlayClasses, placement: this.placement },
            h("anj-time-picker-clock", { context: 'horizontal', locale: this.locale, language: this.language, meridiem: this.meridiem, value: this.value })));
    }
    static get is() { return "anj-time-picker"; }
    static get originalStyleUrls() { return {
        "$": ["time-picker.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["time-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
        },
        "inputId": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "The time picker id"
            },
            "attribute": "input-id",
            "reflect": false,
            "defaultValue": "`anj-time-picker-${inputId++}`"
        },
        "meridiem": {
            "type": "boolean",
            "mutable": false,
            "complexType": {
                "original": "boolean",
                "resolved": "boolean",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Bool to display time in meridiem or military"
            },
            "attribute": "meridiem",
            "reflect": false,
            "defaultValue": "true"
        },
        "max": {
            "type": "string",
            "mutable": true,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Enforce max time for selection"
            },
            "attribute": "max",
            "reflect": false
        },
        "min": {
            "type": "string",
            "mutable": true,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Enforce min time for selection"
            },
            "attribute": "min",
            "reflect": false
        },
        "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'"
        },
        "timezone": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Timezone string to display next to the time on the input"
            },
            "attribute": "timezone",
            "reflect": false
        },
        "value": {
            "type": "any",
            "mutable": true,
            "complexType": {
                "original": "any | null",
                "resolved": "any",
                "references": {}
            },
            "required": false,
            "optional": true,
            "docs": {
                "tags": [],
                "text": "the value of the time"
            },
            "attribute": "value",
            "reflect": false
        }
    }; }
    static get events() { return [{
            "method": "anjClockSelection",
            "name": "anjClockSelection",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "Fires when that value is updated"
            },
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            }
        }, {
            "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 time picker",
                "tags": []
            }
        },
        "close": {
            "complexType": {
                "signature": "() => Promise<void>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<void>"
            },
            "docs": {
                "text": "close the time picker",
                "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, currently a pass-through",
                "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 time strings for parity",
                "tags": []
            }
        },
        "innerValue": {
            "complexType": {
                "signature": "() => Promise<any>",
                "parameters": [],
                "references": {
                    "Promise": {
                        "location": "global"
                    }
                },
                "return": "Promise<any>"
            },
            "docs": {
                "text": "",
                "tags": []
            }
        },
        "remoteCustomValidator": {
            "complexType": {
                "signature": "(valueString: string) => 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": "value",
            "methodName": "valueHandler"
        }]; }
}
Tunnel.injectProps(TimePicker, ['locale', 'language']);
