import { Host, h } from "@stencil/core";
import { cls, getId, isEmpty } from "../../utils/helpers";
import Time from "../../utils/time";
import { Lang } from "../../services/lang";
export class XTimepicker {
    constructor() {
        /**
         * Element ID for internal reference
         */
        this.inputId = getId('textarea');
        this.label = undefined;
        this.name = undefined;
        this.info = undefined;
        this.loading = undefined;
        this.cleanable = undefined;
        this.required = undefined;
        this.now = undefined;
        this.width = undefined;
        this.value = '';
        this.isValid = true;
        this.isFocused = undefined;
        this.isLoading = undefined;
        this.isDisabled = undefined;
        this.isVisible = undefined;
        this.hourHandAngle = 0;
        this.minuteHandAngle = 0;
        this.draggingHand = undefined;
        this.timeSelected = new Time();
    }
    /**
     * Watch changes in value property
     */
    watchValue(value) {
        var _a;
        this.timeSelected.parse(value);
        this.calculateAngleFromTime();
        this.internals.setFormValue(this.timeSelected.toString());
        this.el.dispatchEvent(new InputEvent('input', { bubbles: false }));
        this.formValidateCallback(true);
        (_a = this.internals.form) === null || _a === void 0 ? void 0 : _a.dispatchEvent(new InputEvent('input', { bubbles: false }));
    }
    /**
     * This is called when the 'disabled' attribute of the element or or an ancestor <fieldset> is updated
     *
     * @param disabled
     */
    formDisabledCallback(disabled) {
        this.isDisabled = disabled;
    }
    /**
     * This is called when the parent/owner form is reset
     */
    formResetCallback() {
        this.internals.setFormValue('');
    }
    /**
     * This is called when the input is validated
     */
    formValidateCallback(dispatchValidation) {
        if (this.required && isEmpty(this.value)) {
            this.internals.setValidity({ valueMissing: true }, Lang.get('fields.validation.value-missing'));
        }
        else {
            this.internals.setValidity({});
        }
        if (dispatchValidation) {
            this.isValid = this.internals.validity.valid;
            this.onValidateInputEvent.emit(this.internals);
        }
    }
    /**
     * This is called on component will load
     */
    componentWillLoad() {
        if (isEmpty(this.value)) {
            if (this.now) {
                this.timeSelected = Time.now();
            }
            this.value = this.timeSelected.toString();
        }
    }
    /**
     * This is called on component did load
     */
    componentDidLoad() {
        this.clock.addEventListener('mousedown', this.onDragStart.bind(this));
        this.clock.addEventListener('mousemove', this.onDragMove.bind(this));
        this.clock.addEventListener('mouseup', this.onDragEnd.bind(this));
        this.clock.addEventListener('touchstart', this.onDragStart.bind(this));
        this.clock.addEventListener('touchmove', this.onDragMove.bind(this));
        this.clock.addEventListener('touchend', this.onDragEnd.bind(this));
        this.timeSelected.parse(this.value);
        setTimeout(() => {
            this.calculateAngleFromTime();
            this.formValidateCallback();
        }, 0);
    }
    /**
     * Set element value by event
     *
     * @param event
     */
    onInput(event) {
        const input = event.target;
        console.log(input.value, parseInt(input.value));
        if (input.classList.contains('hour-input')) {
            this.timeSelected.setPeriodHour(parseInt(input.value));
        }
        if (input.classList.contains('min-input')) {
            this.timeSelected.setMinute(parseInt(input.value));
        }
        if (input.classList.contains('period-input')) {
            this.timeSelected.setPeriodHour(this.timeSelected.hour, input.value);
        }
        this.value = this.timeSelected.toString();
    }
    /**
     * Set element value by keyboard event
     */
    onKeydownInput(event) {
        const value = parseInt(event.target.value);
        const max = parseInt(event.target.max);
        const input = event.target;
        if (!['ArrowUp', 'ArrowDown'].includes(event.key)) {
            return;
        }
        if (event.key === 'ArrowUp') {
            if (value < max) {
                input.value = (value + 1).toString().padStart(2, '0');
            }
            else {
                input.value = input.classList.contains('hour-input') ? '01' : '00';
            }
        }
        if (event.key === 'ArrowDown') {
            if (input.classList.contains('hour-input') ? value > 1 : value > 0) {
                input.value = (value - 1).toString().padStart(2, '0');
            }
            else {
                input.value = max.toString().padStart(2, '0');
            }
        }
        input.dispatchEvent(new InputEvent('input'));
    }
    /**
     * This called on input field is unfocused
     */
    onBlurInput(e) {
        const input = e.target;
        if (input.classList.contains('hour-input')) {
            this.hourHand.classList.remove('focus');
        }
        if (input.classList.contains('min-input')) {
            this.minuteHand.classList.remove('focus');
        }
        this.blurTimeout = setTimeout(() => {
            this.isFocused = false;
            this.isVisible = false;
            this.formValidateCallback(true);
        }, 50);
    }
    /**
     * This called on input field is focused
     */
    onFocusInput(e) {
        clearTimeout(this.blurTimeout);
        this.isFocused = true;
        this.isVisible = true;
        const input = e.target;
        if (input.classList.contains('hour-input')) {
            this.hourHand.classList.add('focus');
        }
        if (input.classList.contains('min-input')) {
            this.minuteHand.classList.add('focus');
        }
    }
    /**
     * On drag start event
     */
    onDragStart(event) {
        let target = event.target;
        if (event instanceof TouchEvent) {
            event.preventDefault();
            target = document.elementFromPoint(event.touches[0].clientX, event.touches[0].clientY);
        }
        if (target.tagName === 'SPAN') {
            target = target.parentElement;
        }
        if (target === this.hourHand || target === this.minuteHand) {
            this.draggingHand = target;
        }
        else {
            this.draggingHand = null;
        }
    }
    /**
     * On drag move event
     */
    onDragMove(event) {
        if (this.draggingHand && [this.hourHand, this.minuteHand].includes(this.draggingHand)) {
            if (event instanceof TouchEvent) {
                event.preventDefault();
            }
            const rect = this.clock.getBoundingClientRect();
            const centerX = rect.left + rect.width / 2;
            const centerY = rect.top + rect.height / 2;
            const deltaX = (event instanceof TouchEvent ? event.touches[0] : event).clientX - centerX;
            const deltaY = (event instanceof TouchEvent ? event.touches[0] : event).clientY - centerY;
            let angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI) + 90;
            angle = (angle + 360) % 360;
            if (this.draggingHand === this.minuteHand) {
                this.timeSelected.setMinute(Math.round(angle / 6) % 60);
            }
            else if (this.draggingHand === this.hourHand) {
                this.timeSelected.setPeriodHour(Math.round(angle / 30) % 12 || 12);
            }
            this.value = this.timeSelected.toString();
        }
    }
    /**
     * On drag end event
     */
    onDragEnd() {
        this.draggingHand = null;
    }
    /**
     * Clears the input value
     */
    clearInput() {
        this.timeSelected.setPeriodHour(0, 'am');
        this.timeSelected.setMinute(0);
        this.value = this.timeSelected.toString();
    }
    /**
     * Handle hour button click
     */
    handleHourClick(hour) {
        this.timeSelected.setPeriodHour(hour);
        this.value = this.timeSelected.toString();
    }
    /**
     * Handle minute button click
     */
    handleMinuteClick(min) {
        this.timeSelected.setMinute(min);
        this.value = this.timeSelected.toString();
    }
    /**
     * Get hour position styles
     */
    getHourPosition(hour) {
        const angle = (hour - 3) * (Math.PI / 6);
        const x = 50 + 38 * Math.cos(angle);
        const y = 50 + 38 * Math.sin(angle);
        return {
            left: `${x}%`,
            top: `${y}%`,
        };
    }
    /**
     * Calculate the hand angle from the time
     */
    calculateAngleFromTime() {
        this.hourHandAngle = this.timeSelected.hour * 30;
        this.minuteHandAngle = this.timeSelected.minute * 6;
    }
    /**
     * Get tick position styles
     */
    getTickPosition(i) {
        const angle = (i - 15) * 6 * (Math.PI / 180);
        const x = 50 + 50 * Math.cos(angle);
        const y = 50 + 50 * Math.sin(angle);
        return {
            left: `${x}%`,
            top: `${y}%`,
            transform: `translate(-50%, -50%) rotate(${i * 6}deg)`,
        };
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: '82f3764845d5190c244d8022749852fbea371e13', "data-for": this.name, tabindex: "0", onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e), style: { maxWidth: this.width } }, h("div", { key: '113bad170edcbd3af85e83a27671130651a04f9d', class: cls({
                "input-container": true,
                "focus": this.isFocused,
                "loading": this.loading || this.isLoading,
                "disabled": this.isDisabled,
                "required": this.required,
                "invalid": !this.isValid
            }) }, h("div", { key: '09efd566ed969848c668842373b232ecb04f9699', class: "indicator" }, h("slot", { key: '80e954fe5e2a974161ba94feb5cc9201f3df53a3', name: "indicator" })), h("div", { key: 'be137297ef30f51a73f7761089af1251c40313d3', class: "separator" }), h("div", { key: '79aa1570b1890171b172f95ee336fd05fc30ed95', class: "wrap" }, this.label && h("label", { key: 'f76215379710eed880a9b11782594be280f44abb', htmlFor: `min-${this.inputId}` }, this.label), h("div", { key: '7411d821584225b703b12019270bdf12479032c3' }, h("input", { key: '7425778b99032af9b622d66b762f34f581101618', class: "hour-input", id: `hour-${this.inputId}`, type: "tel", placeholder: "00", max: 12, maxlength: 2, disabled: this.isDisabled || this.isLoading, value: Number.isNaN(this.timeSelected.hour) ? null : this.timeSelected.getPeriodHour().toString().padStart(2, '0'), onInput: (e) => this.onInput(e), onKeyDown: (e) => this.onKeydownInput(e), onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e) }), h("span", { key: '28f4c7812ab6942e9df570f1867cb2adf48231ca' }, ":"), h("input", { key: '3b0613ebfad492b29507198beb965698dfd70d11', class: "min-input", id: `min-${this.inputId}`, type: "tel", placeholder: "00", max: 59, maxlength: 2, disabled: this.isDisabled || this.isLoading, value: Number.isNaN(this.timeSelected.minute) ? null : this.timeSelected.minute.toString().padStart(2, '0'), onInput: (e) => this.onInput(e), onKeyDown: (e) => this.onKeydownInput(e), onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e) }), h("select", { key: 'fcb8971ca9a9c544a07623734cbcc319da82754f', class: "period-input", id: `period-${this.inputId}`, disabled: this.isDisabled || this.isLoading, onInput: (e) => this.onInput(e), onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e) }, h("option", { key: 'b36ed4c209a02e0395fd709092a4c7b3b1d33a4d', value: "am", selected: this.timeSelected.getPeriod() === 'am' }, "AM"), h("option", { key: '7fcbbc074815fd11e322dd5f064cdc80f639554e', value: "pm", selected: this.timeSelected.getPeriod() === 'pm' }, "PM")))), this.loading && h("div", { key: '8dc0b4edc937b7d57a38ef0b5c69fa3b110601c4', class: "loading-indicator" }), h("div", { key: 'ca82fd1d1e8bac522c88f74f320cdbb8697ca379', class: "buttons" }, this.cleanable && h("x-button", { key: '2235946c0f98f190c5a1f48d569014dfed78e5af', icon: "backclear", onClick: () => this.clearInput() }), h("slot", { key: '72fbf6bc7f82b1ab9242a2d0f1a5cd8430c1760f', name: "buttons" })), this.info && h("div", { key: 'a051266d5bdb34b373e568a4321fe0827e270d09', class: "info" }, h("x-tooltip", { key: 'b6aa3b478df8d8e4ee58fd1154da73872d0296be', content: this.info }, h("x-icon", { key: '490b67c714472a7679759537e81cdc96897058c1', name: "info" }))), h("slot", { key: 'e47383acabdd5979398022529ec811ebf8fb20f1' })), h("div", { key: 'bd7a07038c8ae8b1d35eabc5733f18f9f0248d21', class: cls('timepicker', {
                'active': this.isVisible,
            }) }, h("div", { key: 'c729199064edc72f00e7daa3d4337556939ae5dc', class: "arrow" }), h("div", { key: '6a58fa24664ffee46a9d7c0fdaa828eac3b00235', class: cls('clock', {
                'dragging': this.draggingHand,
            }), ref: el => this.clock = el }, [...Array(12).keys()].map(i => {
            const hour = i + 1;
            return h("button", { type: "button", class: "hour", style: this.getHourPosition(hour), onClick: () => this.handleHourClick(hour) }, hour);
        }), [...Array(60).keys()].map(i => {
            return h("button", { type: "button", class: cls(i % 5 === 0 ? 'hour-tick' : 'min-tick'), style: this.getTickPosition(i), onClick: () => this.handleMinuteClick(i) });
        }), h("div", { key: 'd56f0ce7b1eedc41c63271373134f71134fe8d05', ref: el => this.minuteHand = el, class: cls('minute-hand', {
                'active': this.draggingHand === this.minuteHand,
            }), style: { transform: `translate(-50%, -100%) rotate(${this.minuteHandAngle}deg)` } }, h("span", { key: 'd4d58e6ef85efe8da8e35fa3df97742ab5e1eaaf' })), h("div", { key: '8787fbdc215698b013a15ba771feb137099e0ef9', ref: el => this.hourHand = el, class: cls('hour-hand', {
                'active': this.draggingHand === this.hourHand,
            }), style: { transform: `translate(-50%, -100%) rotate(${this.hourHandAngle}deg)` } }, h("span", { key: 'e01151de0cee5dc3d863e849ce650d76ab1fcbe0' })))));
    }
    static get is() { return "x-timepicker"; }
    static get formAssociated() { return true; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input label text"
                },
                "attribute": "label",
                "reflect": false
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input name for forms keys"
                },
                "attribute": "name",
                "reflect": false
            },
            "info": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input information block"
                },
                "attribute": "info",
                "reflect": false
            },
            "loading": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element show loading and block for edit"
                },
                "attribute": "loading",
                "reflect": false
            },
            "cleanable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input clear button"
                },
                "attribute": "cleanable",
                "reflect": false
            },
            "required": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element input required for forms validations"
                },
                "attribute": "required",
                "reflect": false
            },
            "now": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element on empty value set now time"
                },
                "attribute": "now",
                "reflect": false
            },
            "width": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input width"
                },
                "attribute": "width",
                "reflect": false
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string | null",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element input value"
                },
                "attribute": "value",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "isValid": {},
            "isFocused": {},
            "isLoading": {},
            "isDisabled": {},
            "isVisible": {},
            "hourHandAngle": {},
            "minuteHandAngle": {},
            "draggingHand": {},
            "timeSelected": {}
        };
    }
    static get events() {
        return [{
                "method": "onValidateInputEvent",
                "name": "validated",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "On validate input event"
                },
                "complexType": {
                    "original": "ElementInternals",
                    "resolved": "ElementInternals",
                    "references": {
                        "ElementInternals": {
                            "location": "global",
                            "id": "global::ElementInternals"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "watchValue"
            }];
    }
    static get attachInternalsMemberName() { return "internals"; }
}
