import { ConditionalDisplayElement } from '../base/conditional-display-element';
import { Guid } from '../../utils/guid';
import { DisplayMode, GlobalSettings } from '../../settings';
import { TextElementModal } from '../shared/text/text-element';
import { LOCALIZATION } from '../../localization';
import { isNil } from 'lodash';
export class VideoElement extends ConditionalDisplayElement {
    constructor(element, injector, permissionChecker, variableCommunicator, variableStore, videoService, guiSize, svgRootClass, signalRAppId) {
        super(element, permissionChecker, variableCommunicator, variableStore, signalRAppId);
        this.videoService = videoService;
        this.guiSize = guiSize;
        this.svgRootClass = svgRootClass;
        this.videoId = '';
        this.isFullscreen = false;
        this.isMobileMode = DisplayMode.Mobile === injector.get(GlobalSettings).displayMode;
        this.localization = injector.get(LOCALIZATION);
        this.init();
    }
    dispose() {
        if (this.videoPlayer && typeof this.videoPlayer.stop === 'function') {
            this.videoPlayer.stop();
        }
        $('div.' + this.svgRootClass + ' video').each(function () {
            $(this).remove();
        });
    }
    hide() {
        super.hide();
        this.isShow = false;
        if (!isNil(this.videoId) && this.videoId !== '') {
            setTimeout(() => {
                $('#' + this.videoId).hide();
            }, 0);
        }
    }
    show() {
        super.show();
        this.isShow = true;
        setTimeout(() => {
            $('#' + this.videoId).show();
        }, 0);
    }
    init() {
        this.rootElement.selectAll('*').remove();
        if (!this.model.videoTag) {
            this.addVideoAddressToolTip(this.localization.unconfiguredVideoAddress);
            return;
        }
        this.videoId = Guid.newGuid().toString('n');
        this.rootElement.append('rect').attr('id', 'rect' + this.videoId).attr('fill', 'transparent')
            .attr('width', this.model.size.width)
            .attr('height', this.model.size.height);
        this.videoService.getVideoUrl(this.model.videoTag).then(result => {
            this.videoUrl = result.url;
            this.initVideo(result.url, this.videoId);
        }).catch(() => {
            throw new Error('Failure of the videoService');
        });
    }
    initVideo(videoUrl, videoId) {
        const patt = /https:.+.m3u8/;
        if (videoUrl.indexOf('http:') !== -1) {
            videoUrl = videoUrl.replace('http:', 'https:');
        }
        if (!patt.test(videoUrl)) {
            let videoToolTip = this.localization.invalidVideoAddress;
            if (isNil(videoUrl) || videoUrl === '') {
                videoToolTip = this.localization.unconfiguredVideoAddress;
            }
            this.addVideoAddressToolTip(videoToolTip);
            return;
        }
        const isAndroid = !!navigator.userAgent.match(/(Android)/i);
        const isIos = !!navigator.userAgent.match(/(Mac)/i);
        const currentRect = this.$element.find('rect#rect' + videoId).first();
        if (!currentRect.length) {
            return;
        }
        const clientRect = currentRect[0].getBoundingClientRect();
        const chartWidth = clientRect.width;
        const chartHeight = clientRect.height;
        const left = this.model.location.x / this.guiSize.width * $('.' + this.svgRootClass).find('.svg-content').width();
        const top = this.model.location.y / this.guiSize.height * $('.' + this.svgRootClass).find('.svg-content').height();
        const scareX = this.model.location.x / this.guiSize.width;
        const scareY = this.model.location.y / this.guiSize.height;
        if (isIos) {
            videoUrl = videoUrl + '#t=1';
        }
        const preload = isIos ? ' preload=\'metadata\'' : '';
        let videoHtml = `<video scareX="${scareX}"
                scareY="${scareY}" id="${videoId}" ${preload} src="${videoUrl}" width="${chartWidth}" height="${chartHeight}"
                style="position: absolute;top:${top}px;left:${left}px;object-fit:fill;z-index:0;"
                playsInline webkit-playsinline `;
        if (this.isMobileMode) {
            if (isAndroid) {
                videoHtml += ' muted></video>';
            }
            else {
                videoHtml += ' controls muted></video>';
            }
        }
        else {
            videoHtml += ' controls autoplay muted></video>';
        }
        $('.' + this.svgRootClass).find('.svg-content').append(videoHtml);
        if (this.isShow === false) {
            $('#' + this.videoId).hide();
        }
        setTimeout(() => {
            if (isAndroid) {
                this.setAndroidVideo(videoId);
            }
            else if (isIos) {
                this.setIosVideo(this.videoUrl, videoId);
            }
            try {
                this.videoPlayer = new EZUIPlayer(videoId);
                if (isAndroid) {
                    // 确保在 EZUIPlayer 初始化后才调用 play 方法
                    this.videoPlayer.on('canplay', () => {
                        this.videoPlayer.play();
                    });
                }
            }
            catch (err) {
                console.log(err);
            }
        }, 1000);
        const style = document.createElement('style');
        style.innerHTML = `#${videoId}::-webkit-media-controls-enclosure {
            display: none;
        }`;
        document.head.append();
    }
    addVideoAddressToolTip(videoToolTip) {
        const size = this.model.size;
        this.rootElement.append('image')
            .attr('width', size.width)
            .attr('height', size.height)
            .attr('xlink:href', 'assets/img/video.jpg')
            .attr('preserveAspectRatio', 'none')
            .attr('crossorigin', 'anonymous');
        const font = {
            isUnderline: false,
            isBold: false,
            isItalic: false,
            fontSize: '16px',
            fontFamily: 'Microsoft YaHei',
            color: '#fff',
            textAlign: 'center'
        };
        const textElement = new TextElementModal(videoToolTip, font, size.width, size.height);
        this.$element.append(textElement.Element);
    }
    setAndroidVideo(videoId) {
        const videoElement = $('#' + videoId);
        let preHeight = videoElement.height();
        let preWidth = videoElement.width();
        let preTop = videoElement.css('top');
        let preLeft = videoElement.css('left');
        const { StatusBar } = window;
        videoElement.on('click', () => {
            if (!this.isFullscreen) {
                if (StatusBar) {
                    StatusBar.hide();
                }
                preHeight = videoElement.height();
                preWidth = videoElement.width();
                preTop = videoElement.css('top');
                preLeft = videoElement.css('left');
                const width = document.documentElement.clientWidth;
                const height = document.documentElement.clientHeight;
                videoElement.css('object-fit', 'contain');
                videoElement.css('background', '#000000');
                videoElement.css('width', width + 'px');
                videoElement.css('height', height + 'px');
                videoElement.css('left', '0px');
                videoElement.css('top', '0px');
                videoElement.css('z-index', '99');
                videoElement.css('position', 'fixed');
                this.isFullscreen = true;
                try {
                    screen.orientation.lock(screen.orientation.type);
                }
                catch (error) {
                    console.error(error);
                }
            }
            else {
                videoElement.css('object-fit', 'fill');
                videoElement.css('width', preWidth + 'px');
                videoElement.css('height', preHeight + 'px');
                videoElement.css('left', preLeft);
                videoElement.css('top', preTop);
                videoElement.css('z-index', '0');
                videoElement.css('position', 'absolute');
                this.isFullscreen = false;
                try {
                    if (screen.orientation.type.includes('portrait')) {
                        StatusBar.show();
                    }
                }
                catch (error) {
                    console.error(error);
                }
            }
        });
    }
    setIosVideo(videoUrl, videoId) {
        const video = $('#' + this.videoId);
        video.on('webkitendfullscreen', () => {
            video.remove();
            clearTimeout(this.refreshTimer);
            this.refreshTimer = null;
            this.refreshTimer = setTimeout(() => {
                this.initVideo(videoUrl, videoId);
            }, 500);
        });
    }
}
