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.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 }));
            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: '314f24bb0d75056accafbb6c7354379bbabf23ab' }, h("div", { key: 'e50c6a575dacc530c63bd0ad0723fe4104fd5a21', class: "media-container" }, this.getMainElementRender(), h("div", { key: 'eba7d452f61289d253b3780f736b9ce8cb2d47f4', class: "media-actions" }, h("slot", { key: '32656ad1b5ce607ebc7f7a3c26197b3556928e66', name: "actions" }))), h("div", { key: '3fa69ad072e0e4d28efcd3698d1ea509b79a7966', class: "item-selector" }, this.isLeftArrowActive && h("button", { key: '43708c5902a36fd87140feb428127c051aa0ee4a', disabled: this.busyScroll, onClick: () => this.onScrollLeft() }, h("x-icon", { key: '7ec79bbba5847f6a72a9f9c18ee895ca52bc566c', name: "back" })), h("slot", { key: 'fad63eeee295cb189b02abce1c5cf7a5678cc778' }), h("div", { key: 'f36f847cac508f5b7620a5f8ab9b42e61e935732', 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: 'f88de5054bd6dab08c9be82b9a87d79211a35c28', href: "javascript:;", onClick: () => this.uploadMedia.emit(), class: "upload-action" }, h("x-icon", { key: '5b0b727af20ef3812bc1f517f861abb111204f44', 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: '392f65d6564d1c0934a7c37f94085fdfe42a7b2a', disabled: this.busyScroll, onClick: () => this.onScrollRight() }, h("x-icon", { key: 'ed1a25798f3c1a4640a6ff99b99627b225f79fec', 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"
            }
        };
    }
    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
            }];
    }
}
