import { Host, h } from "@stencil/core";
import { cls } from "../../utils/helpers";
const TIME_THRESHOLD = 100;
const SWIPE_THRESHOLD = 20;
export class XShowcase {
    constructor() {
        /**
         * Element active scroll timeout
         */
        this.activeScroll = null;
        /**
         * Total time that the swipe took
         */
        this.touchTotalTime = 0;
        this.upload = false;
        this.minHeight = undefined;
        this.isLeftArrowActive = false;
        this.isRightArrowActive = false;
        this.activeMediaIndex = 0;
        this.busyScroll = false;
        this.mediaElements = [];
    }
    /**
     * Element event on slot make changes
     *
     * @param evt
     */
    handleSlotChange() {
        this.searchMediaElements();
    }
    /**
     * On component will load action
     */
    componentWillLoad() {
        this.searchMediaElements();
    }
    /**
     * This is called on component did load
     */
    componentDidLoad() {
        setTimeout(() => {
            this.onContainerScroll();
            if (this.container) {
                this.isRightArrowActive = this.container.scrollWidth > this.container.offsetWidth;
            }
        }, 0);
    }
    /**
     * Register all the child elements
     */
    searchMediaElements() {
        this.mediaElements = Array.from(this.el.children)
            .filter(item => item.nodeName.toLowerCase() === 'x-showcase-item')
            .map(el => el);
    }
    /**
     * Event on container scroll with buttons
     */
    onContainerScroll() {
        if (!this.container) {
            return;
        }
        this.busyScroll = true;
        if (this.activeScroll !== null) {
            clearTimeout(this.activeScroll);
        }
        this.activeScroll = setTimeout(() => {
            this.isLeftArrowActive = this.container.scrollLeft > 0;
            this.isRightArrowActive = this.container.scrollLeft < this.container.scrollWidth - this.container.offsetWidth;
            this.busyScroll = false;
        }, 200);
    }
    /**
     * On scroll left button event
     */
    onScrollLeft() {
        this.scrollItemTo(-1);
    }
    /**
     * On scroll right button event
     */
    onScrollRight() {
        this.scrollItemTo(1);
    }
    /**
     * On select item event
     */
    onSelectMedia(event, index) {
        event.preventDefault();
        this.selectMediaElement(index);
    }
    /**
     * On swipe start
     */
    onTouchStart(e) {
        this.touchStart = e.touches[0].clientX;
        this.touchTime = setInterval(() => {
            this.touchTotalTime += 10;
        }, 10);
    }
    /**
     * On swipe end
     */
    onTouchEnd(e) {
        const endX = e.changedTouches[0].clientX;
        if (typeof endX !== "number")
            return;
        clearInterval(this.touchTime);
        if (this.touchTotalTime >= TIME_THRESHOLD) {
            if (this.touchStart > endX && this.touchStart - endX >= SWIPE_THRESHOLD) {
                this.onScrollRight();
            }
            else if (this.touchStart < endX && endX - this.touchStart >= SWIPE_THRESHOLD) {
                this.onScrollLeft();
            }
        }
        this.touchTotalTime = 0;
    }
    /**
     * Handle scroll position to item
     */
    scrollItemTo(positionFactor) {
        const container = this.el.querySelector(".items");
        if (container) {
            const factor = Math.round(container.offsetWidth / 58);
            const position = (factor - 1) * 58;
            container.scrollBy({
                top: 0,
                left: position > 200 ? positionFactor * position : positionFactor * 200,
                behavior: "smooth",
            });
        }
    }
    selectMediaElement(index) {
        if (index != null && this.mediaElements[index]) {
            this.activeMediaIndex = index;
            this.selectMedia.emit({
                index: index,
                el: this.mediaElements[index],
                target: this.el.querySelector('.media-container img, .media-container iframe'),
            });
        }
    }
    /**
     * Get the Youtube video media thumb
     */
    getMediaThumb(media) {
        if (media.type == "youtube") {
            return `http://img.youtube.com/vi/${this.getYoutubeId(media.url)}/0.jpg`;
        }
        return media.thumb || media.url;
    }
    /**
     * Obtain the Youtube ID reference from URL
     */
    getYoutubeId(url) {
        const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
        const match = regExp.exec(url);
        return match && match[7].length == 11 ? match[7] : false;
    }
    /**
     * Return the item element container
     */
    getMainElementRender() {
        if (!this.mediaElements[this.activeMediaIndex]) {
            return (h("slot", { name: "empty" }, h("div", { class: "empty" }, h("x-icon", { name: "image", size: "8rem" }))));
        }
        switch (this.mediaElements[this.activeMediaIndex].type) {
            case 'image':
                return (h("img", { src: this.mediaElements[this.activeMediaIndex].url, "aria-label": this.mediaElements[this.activeMediaIndex].title, alt: this.mediaElements[this.activeMediaIndex].title, style: {
                        width: this.mediaElements[this.activeMediaIndex].width,
                        height: this.mediaElements[this.activeMediaIndex].height,
                        minHeight: this.minHeight,
                    } }));
            case 'youtube':
                return (h("iframe", { src: this.mediaElements[this.activeMediaIndex].url, title: this.mediaElements[this.activeMediaIndex].title, height: "420", scrolling: "no", frameborder: "0", allowFullScreen: true, allow: "autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" }));
            default:
                return (h("x-skeleton", { block: true, height: "16rem" }));
        }
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: '91d8885468cf6a3f372244975ac400b39e93fcf9' }, h("div", { key: '28e3fe35c9c89fc03fdf0b87e6b9bcefd7c912ca', class: "media-container" }, this.getMainElementRender(), h("div", { key: 'dd05b0f139ee3fcd2a2993bc23b1d097505ee417', class: "media-actions" }, h("slot", { key: 'a8f5e16d337c3caa7fb43ac8fc2d7c1a9034d6b2', name: "actions" }))), h("div", { key: '588d98d90106243c65dbcc888d8dd44966dd9223', class: "item-selector" }, this.isLeftArrowActive && h("button", { key: '2fa9de8b34ccd6581cb1948dbd70efd98f164f85', disabled: this.busyScroll, onClick: () => this.onScrollLeft() }, h("x-icon", { key: '3c96c3826bc384f39ce3435634e16fd3a742d0b8', name: "back" })), h("slot", { key: 'b436dfa17621a9fdccb1f16492114b50b62d7bc7' }), h("div", { key: '0b2378ef91e203a944b29480c7a25b5658f697fc', class: "items", ref: el => this.container = el, onScroll: () => this.onContainerScroll(), onTouchStart: e => this.onTouchStart(e), onTouchEnd: e => this.onTouchEnd(e) }, this.upload && h("a", { key: '0634ba6cb5d50035c686a1a0111f0ac2ad694fa5', href: "javascript:;", onClick: () => this.uploadMedia.emit(), class: "upload-action" }, h("x-icon", { key: 'b25b51df596e2cd8a2d95a7c7aef55df60cf60c1', name: "plus", size: "1.5rem" })), this.mediaElements.map((media, i) => (h("a", { onClick: (e) => this.onSelectMedia(e, i), key: i, href: media.url, style: { backgroundImage: this.getMediaThumb(media) ? `url(${this.getMediaThumb(media)})` : null }, class: cls({ selected: i == this.activeMediaIndex }) }, ['youtube', 'video'].includes(media.type) && h("svg", { x: "0px", y: "0px", viewBox: "0 0 700 700" }, h("g", null, h("path", { d: "M350,87.4c-106.2,0-192.6,86.5-192.6,192.6S243.8,472.6,350,472.6S542.6,386.2,542.6,280S456.2,87.4,350,87.4L350,87.4z\n\t\t\t\t\t\t\t\t\t\t\tM433.3,286.7c-1.3,2.2-2.7,3.6-4.9,4.9l-116.5,67.2c-2.2,1.3-4.5,1.8-6.7,1.8c-7.6,0-13.4-5.8-13.4-13.4V212.8\n\t\t\t\t\t\t\t\t\t\t\tc0-7.6,5.8-13.4,13.4-13.4c2.2,0,4.5,0.4,6.7,1.8l116.5,67.2C434.7,271.9,436.9,280.4,433.3,286.7L433.3,286.7z" }))))))), this.isRightArrowActive && h("button", { key: 'eda8440de9f1517fe2d67593facf37e51d70eeea', disabled: this.busyScroll, onClick: () => this.onScrollRight() }, h("x-icon", { key: 'c676e419b506b2a66f11a3ec91fe29dcf8712361', name: "forward" }))));
    }
    static get is() { return "x-showcase"; }
    static get originalStyleUrls() {
        return {
            "$": ["./style.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["style.css"]
        };
    }
    static get properties() {
        return {
            "upload": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Element is upload media"
                },
                "attribute": "upload",
                "reflect": false,
                "defaultValue": "false"
            },
            "minHeight": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Element min height"
                },
                "attribute": "min-height",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "isLeftArrowActive": {},
            "isRightArrowActive": {},
            "activeMediaIndex": {},
            "busyScroll": {},
            "mediaElements": {}
        };
    }
    static get events() {
        return [{
                "method": "uploadMedia",
                "name": "uploadMedia",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Element upload media event"
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "selectMedia",
                "name": "selectMedia",
                "bubbles": false,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Element select media event"
                },
                "complexType": {
                    "original": "SelectedMedia",
                    "resolved": "SelectedMedia",
                    "references": {
                        "SelectedMedia": {
                            "location": "local",
                            "path": "/opt/atlassian/pipelines/agent/build/src/components/x-showcase/component.tsx",
                            "id": "src/components/x-showcase/component.tsx::SelectedMedia"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get listeners() {
        return [{
                "name": "slotchange",
                "method": "handleSlotChange",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
