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("x-skeleton", { height: "16rem" }));
        }
        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", { height: "16rem" }));
        }
    }
    /**
     * Render component
     */
    render() {
        return h(Host, { key: '0195f29794e97b0a6ad7834a68a92adc37c46688' }, h("div", { key: 'f05a26a5ab3a1e1bcd586ef2932a6d09ac6f7355', class: "media-container" }, this.getMainElementRender(), h("div", { key: '1cd98eadb112f6e8f159000d2376626be47e015a', class: "media-actions" }, h("slot", { key: '2ae485f790704ca416376a8ed792f89c5e412c20', name: "actions" }))), h("div", { key: '3dcd24a2d4dca62cae75405a7d578c2c6f5e6b23', class: "item-selector" }, this.isLeftArrowActive && h("button", { key: '2d18d7dfe44e8524548be991dac47087fb56778f', disabled: this.busyScroll, onClick: () => this.onScrollLeft() }, h("x-icon", { key: '358e80ac6321cc411847a7f0b1f97246931c27cb', name: "back" })), h("slot", { key: 'd527de14bccf385c34c81894caac785731f738cb' }), h("div", { key: 'ffe9bf3ae31be6bae4be67fe91ae8cdc4df4f401', 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: 'e4f3a1b61031771fc56cfe45f7faf710e2440eeb', href: "javascript:;", onClick: () => this.uploadMedia.emit(), class: "upload-action" }, h("x-icon", { key: '9fe1873a25c810369d56acd2a0c57694b92c352a', 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: '7ed3e8e2505c0ea77ad0485974c183d067a24b0d', disabled: this.busyScroll, onClick: () => this.onScrollRight() }, h("x-icon", { key: '97596b63a0e63636d971912ae1172855f0867ee2', 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
            }];
    }
}
