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.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: '7cf7c3e2b3c5c048e1d1f4daf5e8d313289e30ef', "data-for": this.name, tabindex: "0", onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e) }, h("div", { key: 'd832de92bfdb2ba16451f188c34144aedca6936c', 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: 'b3bb6d64d64f69b8def66854900a573d5a50346a', class: "indicator" }, h("slot", { key: '0b7bf354fd685277bf0bf2bca9707950d2d3fc0d', name: "indicator" })), h("div", { key: 'ab78832a05d19f38ff8cd338eae11132b5b1433e', class: "separator" }), h("div", { key: '8764d9d8f44cd64a362948c49a0cb6f837b1d8e9', class: "wrap" }, this.label && h("label", { key: 'cc34b01f0d86c5515117ad20d933f2a07b7dcda1', htmlFor: `min-${this.inputId}` }, this.label), h("div", { key: 'a4c59907bae41ff0816494686ae37945731dad09' }, h("input", { key: '617c7698d5f0527dc42f942260a70ed1c22989a1', 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: '164d8d955b6b7f91b4b0f2f97dba492412a10919' }, ":"), h("input", { key: 'fbf0c0ca84b377ae2b47105b4b090e804b87bc3f', 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: '979b24457c93ced1026856b4e6626eb0388d2c8f', 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: '0c2d5920ba54414bef46ea7229bfa8331f0b1977', value: "am", selected: this.timeSelected.getPeriod() === 'am' }, "AM"), h("option", { key: 'eb7dc417256dfe447bd8b28ca29426348a7dafee', value: "pm", selected: this.timeSelected.getPeriod() === 'pm' }, "PM")))), this.loading && h("div", { key: 'f43ec469f09280fce99d0968ade875c9529152e7', class: "loading-indicator" }), h("div", { key: 'ec9183b23c65d1349bb90cdcbc82512cd0f45106', class: "buttons" }, this.cleanable && h("x-button", { key: 'c4655c266798ffa84de066a8a87925b86c772322', icon: "backclear", onClick: () => this.clearInput() }), h("slot", { key: '7eda281d17e030588b7aa34892a46d743e374b5c', name: "buttons" })), this.info && h("div", { key: '9209072d44249a7133c7c83a57752651562c0611', class: "info" }, h("x-tooltip", { key: '5550f5f895e223e0af8647e73ed71031ba179abc', content: this.info }, h("x-icon", { key: '2083fc756690958281870a6d580f16851958f16f', name: "info" }))), h("slot", { key: '0694ff0b78071874a4146f4cf73ff40b0d545874' })), h("div", { key: 'b4232850cf08e1d6250fe678f2ade05b960625bc', class: cls('timepicker', {
                'active': this.isVisible,
            }) }, h("div", { key: '5d0b20c07a0edd9117e6b1fea80f40602b8ee29c', class: "arrow" }), h("div", { key: '7bede7df39ace67514b95192103037bc967218f6', 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: '53f3391281c99078cc4edcc7f4636c5ed2cf4e0b', 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: 'd2f99fb5ff04084d3fe026f85340ae1c9d858ac3' })), h("div", { key: 'd64fc90e6d8932d9f14a041d9122f7de48ec2302', 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: '91c3809d8d589c4e99d5f34adee3b2c7bb92a434' })))));
    }
    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
            },
            "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"; }
}
