import { Host, h } from "@stencil/core";
import { cls, getId } from "../../utils/helpers";
import Time from "../../utils/time";
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.value = '';
        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();
    }
    /**
     * On value attribute change
     *
     * @param value
     */
    onValueChange(value) {
        this.timeSelected.parse(value);
        this.calculateAngleFromTime();
        this.internals.setFormValue(this.timeSelected.toString());
        this.el.dispatchEvent(new InputEvent('input'));
    }
    /**
     * 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 on component did load
     */
    componentDidLoad() {
        this.clock = this.el.querySelector('.clock');
        this.hourHand = this.clock.querySelector('.hour-hand');
        this.minuteHand = this.clock.querySelector('.minute-hand');
        this.clock.addEventListener('mousemove', this.onMouseMove.bind(this));
        this.clock.addEventListener('mouseup', this.onMouseUp.bind(this));
        this.clock.addEventListener('mousedown', this.onMouseDown.bind(this));
        this.timeSelected.parse(this.value);
        this.calculateAngleFromTime();
    }
    /**
     * Set element value by event
     *
     * @param event
     */
    onInput(event) {
        const input = event.target;
        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;
        }, 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 mouse up event
     */
    onMouseUp() {
        this.draggingHand = null;
    }
    /**
     * On mouse down event
     */
    onMouseDown(event) {
        let target = event.target;
        if (target.tagName === 'SPAN') {
            target = target.parentElement;
        }
        if (target === this.hourHand || target === this.minuteHand) {
            this.draggingHand = target;
        }
        else {
            this.draggingHand = null;
        }
    }
    /**
     * On mouse move event
     */
    onMouseMove(event) {
        if (this.draggingHand && [this.hourHand, this.minuteHand].includes(this.draggingHand)) {
            const rect = this.clock.getBoundingClientRect();
            const centerX = rect.left + rect.width / 2;
            const centerY = rect.top + rect.height / 2;
            const deltaX = event.clientX - centerX;
            const deltaY = 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();
        }
    }
    /**
     * 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: 'e535d8155b40ede6387c7b6a16e826814a7bcbc4', "data-for": this.name, tabindex: "0", onFocus: (e) => this.onFocusInput(e), onBlur: (e) => this.onBlurInput(e) }, h("div", { key: '739335f084ae03d37a6e9f9151c6ff32c79d7198', class: cls({
                "input-container": true,
                "focus": this.isFocused,
                "loading": this.loading || this.isLoading,
                "disabled": this.isDisabled,
            }) }, h("div", { key: '48bea852d9a5acc0abf9ee3640b3e50c5715e5e2', class: "indicator" }, h("slot", { key: '6dc895b7b03aa541291cb4a7f12ad69215df6fb3', name: "indicator" })), h("div", { key: '2ab03b999f4829ae37ecf1935e6c1d5e719b3071', class: "separator" }), h("div", { key: 'b58550ff81de491857109d7214eed22534292513', class: "wrap" }, this.label && h("label", { key: 'dea905ba1314dded7bb12da0e509a1fcdac3f053', htmlFor: this.inputId }, this.label), h("div", { key: '3d2285838f72f34b4a0e049ca6e9c186c325d68d' }, h("input", { key: '9679eb6268c1aeccb3e0e26937d8dfffdd665850', class: "hour-input", id: `hour-${this.inputId}`, type: "tel", placeholder: "00", max: 12, maxlength: 2, disabled: this.isDisabled || this.isLoading, value: 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: 'c6ac9afedb892a9e1074005fc1142c470a42f4b9' }, ":"), h("input", { key: '13161e96c792e267b2c4ebdea241e1eef7839d5f', class: "min-input", id: `min-${this.inputId}`, type: "tel", placeholder: "00", max: 59, maxlength: 2, disabled: this.isDisabled || this.isLoading, value: 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: '4be500a490e1a602e55ac6e456903e8bd1086e39', 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: 'd66c29b57f223e7a8778ca70af817559cdc93300', value: "am", selected: this.timeSelected.getPeriod() === 'am' }, "AM"), h("option", { key: 'ad81e8821d3b6944ddf9d0f91692cbddd7c22947', value: "pm", selected: this.timeSelected.getPeriod() === 'pm' }, "PM")))), this.loading && h("div", { key: '67453d9c81f94bfdcacf836167753e802e337ac5', class: "loading-indicator" }), h("div", { key: '831d33ec77852032c5fc317da256f6e94f7da49a', class: "buttons" }, this.cleanable && h("x-button", { key: '719f9ea6e2940d6139e57a54cf63a09a28243866', icon: "backclear", onClick: () => this.clearInput() }), h("slot", { key: '16b427f8999ce3add866fd43e068accba7c9b12b', name: "buttons" })), this.info && h("div", { key: '4eb4b9efda526f931b15818bc4f2aa1ad567355a', class: "info" }, h("x-tooltip", { key: 'cd158c63fb79c05cbe7487a3f6e736c469fb163d', content: this.info }, h("x-icon", { key: '133d9e0f807e0483eb6d7af576c14d4f08ba6e0a', name: "info" }))), h("slot", { key: 'f375485130a99de1e76a8a97b24c2c626b4d50b8' })), h("div", { key: '39f1280fc457cd0d7e809cce5f122ec92155aef2', class: cls('timepicker', {
                'active': this.isVisible,
            }) }, h("div", { key: '74af8ab6a7365b2486a406af0ea3e6d0536f7182', class: "arrow" }), h("div", { key: 'c84b34c1334f79d91a1c111ef46468b23dc0f595', class: cls('clock', {
                'dragging': this.draggingHand,
            }) }, [...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: 'ef1baef3b88797409ed2d7eb589284f05424792e', class: cls('minute-hand', {
                'active': this.draggingHand === this.minuteHand,
            }), style: { transform: `translate(-50%, -100%) rotate(${this.minuteHandAngle}deg)` } }, h("span", { key: '1f0d9c1a5cda3e7ee74684b6c47b1ce5819e0140' })), h("div", { key: 'f550ab70bea901e87032048c933d8af19b53b184', class: cls('hour-hand', {
                'active': this.draggingHand === this.hourHand,
            }), style: { transform: `translate(-50%, -100%) rotate(${this.hourHandAngle}deg)` } }, h("span", { key: '9ab05bbd49695259ffd98bc5498b001e5dca3054' })))));
    }
    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
            },
            "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 {
            "isFocused": {},
            "isLoading": {},
            "isDisabled": {},
            "isVisible": {},
            "hourHandAngle": {},
            "minuteHandAngle": {},
            "draggingHand": {},
            "timeSelected": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "onValueChange"
            }];
    }
    static get attachInternalsMemberName() { return "internals"; }
}
