/* eslint-disable @typescript-eslint/no-non-null-assertion */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
// #region Imports
import { CustomElement } from '../../Abstracts/CustomElement';
import { epgProgramElementTemplate } from './EpgProgramElementTemplate';
import { epgProgramElementJoyStyle } from './Themes/EpgProgramElement.Joy';
import { Component } from '../../..//Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Listen } from '../../../../Events/Decorators/ListenDecorator';
import { Key } from '../../../Types/Key';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Focusable } from '../../../Behaviors/Focusable';
import { TextElement } from '../../Primitives/Text/TextElement';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { Variantable } from '../../../Behaviors/Variantable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Boundable } from '../../../Behaviors/Boundable';
import { Localeable } from '../../../Behaviors/Localeable';
import { FilterableChild } from '../../../Behaviors/Filterable';
// #endregion
/**
 * The `{@link EpgProgramElement}` element.
 *
 * @public
 */
let EpgProgramElement = class EpgProgramElement extends FilterableChild(Localeable(Boundable(Variantable(Appearanceable(Disableable(Focusable(Valueable(CustomElement)))))))) {
    // #region Fields
    _keyboardController;
    _boardElement;
    _header;
    _lane;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._boardElement = null;
        this._header = '';
        this._lane = 0;
        this._keyboardController = new KeyboardController(this);
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-epg-program';
    }
    /**
     * Gets or sets the `header` property.
     *
     * @public
     */
    get header() {
        return this._header;
    }
    set header(value) {
        if (this._header !== value) {
            this._header = value;
            this.requestUpdate('header');
        }
    }
    /**
     * Gets or sets the `lane` property.
     *
     * @public
     * @attr
     */
    get lane() { return this._lane; }
    set lane(value) {
        if (this._lane !== value) {
            this._lane = value;
            this.requestUpdate('lane');
        }
    }
    get root() {
        return this._boardElement;
    }
    /**
     * Gets the `displayText` property.
     *
     * @public
     * @readonly
     * @hidden
     */
    get displayText() {
        return this.textContent?.trim() ?? '';
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this._keyboardController
            .add([Key.Space, Key.Enter], (e) => {
            this.dispatchEvent(new CustomEvent('select', { detail: this }));
            e?.stopPropagation();
            e?.preventDefault();
        }, undefined, { preventDefault: true })
            .add([Key.UpArrow, Key.LeftArrow, Key.UpArrow, Key.DownArrow], (e) => {
            const all = Array.from(document.querySelectorAll('epg-program'));
            const idx = all.indexOf(this);
            let next = undefined;
            switch (e?.key ?? '') {
                case 'ArrowRight':
                    next = all[idx + 1];
                    break;
                case 'ArrowLeft':
                    next = all[idx - 1];
                    break;
                case 'ArrowDown':
                    next = all.find((el) => el !== this && Math.abs(el.getBoundingClientRect().top - this.getBoundingClientRect().top) > 60);
                    break;
                case 'ArrowUp':
                    next = [...all].reverse().find((el) => el !== this && Math.abs(el.getBoundingClientRect().top - this.getBoundingClientRect().top) > 60);
                    break;
                default:
                    next = undefined;
                    break;
            }
            if (next instanceof HTMLElement) {
                next.focus();
                e?.preventDefault();
            }
        }, undefined, { preventDefault: true });
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._boardElement = DomServiceLocator.current.findAncestor(this, 'mosaik-epg', { strict: true });
        // this._boardElement.on('changed', (e) => {
        //     if (e.detail.propertyName === 'zoomMinutes') {
        //         this.setPosition();
        //     }
        // });
        this.calculatePosition();
    }
    onClick(_) {
        if (this.disabled) {
            return;
        }
        this.dispatchEvent(new CustomEvent('select', { detail: this }));
        // e.stopPropagation();
        // e.preventDefault();
    }
    /**
     * Calculates the program block position (left, width, top, height).
     *
     * @private
     */
    calculatePosition() {
        const board = this._boardElement;
        if (board) {
            const startMs = this.start.getTime() - board.start.getTime();
            const durationMs = this.end.getTime() - this.start.getTime();
            this.style.setProperty('--_since-ms', `${startMs}`);
            this.style.setProperty('--_duration-ms', `${durationMs}`);
            this.style.setProperty('--_lane', `${this.lane}`);
            this.style.setProperty('--epg-program-left', 'calc(var(--_since-ms) / var(--_ms-per-hour) * var(--_hour-width))');
            this.style.setProperty('--epg-program-width', 'calc(var(--_duration-ms) / var(--_ms-per-hour) * var(--_hour-width))');
            this.style.setProperty('--epg-program-top', 'calc(var(--_lane) * var(--_lane-height))');
            this.style.setProperty('--epg-program-height', 'var(--_lane-height)');
        }
        else {
            this.style.setProperty('--epg-program-left', '0');
            this.style.setProperty('--epg-program-width', '0');
            this.style.setProperty('--epg-program-top', '0');
            this.style.setProperty('--epg-program-height', '0');
        }
    }
};
__decorate([
    Property({
        type: String,
        isStyle: true
    }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], EpgProgramElement.prototype, "header", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], EpgProgramElement.prototype, "lane", null);
__decorate([
    Listen('click'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [MouseEvent]),
    __metadata("design:returntype", void 0)
], EpgProgramElement.prototype, "onClick", null);
EpgProgramElement = __decorate([
    Component({
        selector: 'mosaik-epg-program',
        template: epgProgramElementTemplate,
        styles: epgProgramElementJoyStyle,
        host: {
            role: 'button',
            tabIndex: '0'
        },
        imports: [
            FocusRingElement,
            TextElement
        ]
    }),
    __metadata("design:paramtypes", [])
], EpgProgramElement);
export { EpgProgramElement };
//# sourceMappingURL=EpgProgramElement.js.map