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.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.initVideo(result.url, result.isMobileType, this.videoId);
        }).catch(() => {
            throw new Error('Failure of the videoService');
        });
    }
    initVideo(videoUrl, isMobileType, 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 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();
        let videoHtml = `<video scareX="${this.model.location.x / this.guiSize.width}"
    scareY="${this.model.location.y / this.guiSize.height}" id="${videoId}" src="${videoUrl}" style="
    position: absolute;top:${top}px;left:${left}px;width:${chartWidth}px;height:${chartHeight}px;object-fit:fill;z-index:0"
    playsInline webkit-playsinline `;
        const isAndroid = !!navigator.userAgent.match(/(Android)/i);
        if (this.isMobileMode) {
            if (isAndroid) {
                if (isMobileType) {
                    videoHtml += ' controls ';
                }
                videoHtml += ' autoplay 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();
        }
        this.videoPlayer = new EZUIPlayer(videoId);
        if (isAndroid && !isMobileType) {
            this.setAndroidVideo(videoId);
        }
    }
    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) {
        let isFullscreen = false;
        const videoElement = $('#' + videoId);
        let preHeight = videoElement.height();
        let preWidth = videoElement.width();
        let preTop = videoElement.css('top');
        let preLeft = videoElement.css('left');
        videoElement.on('click', () => {
            if (!isFullscreen) {
                preHeight = videoElement.height();
                preWidth = videoElement.width();
                preTop = videoElement.css('top');
                preLeft = videoElement.css('left');
                const width = document.body.clientWidth;
                const height = width * 9 / 16;
                videoElement.css('width', width + 'px');
                videoElement.css('height', height + 'px');
                videoElement.css('left', '0px');
                videoElement.css('top', '0px');
                videoElement.css('z-index', '99');
                isFullscreen = true;
            }
            else {
                videoElement.css('width', preWidth + 'px');
                videoElement.css('height', preHeight + 'px');
                videoElement.css('left', preLeft);
                videoElement.css('top', preTop);
                videoElement.css('z-index', '0');
                isFullscreen = false;
            }
        });
    }
}
