/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration: These technical material reserved as the technical secrets by AGREE 
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer 
 * Software" and other relevant administrative regulations and international treaties. Without 
 * the written permission of the Company, no person may use (including but not limited to the 
 * illegal copy, distribute, display, image, upload, and download) and disclose the above 
 * technical documents to any third party. Otherwise, any infringer shall afford the legal 
 * liability to the company.
 */

import {Widget} from "widget/Widget";

export class ACefNativeWindow extends Widget {

    private static Template: string = `
           <div>
               <embed width="100%" height="100%" type="application/x-nativewindow"></embed>
           </div>`;
    private $plugin: JQuery;

    private windowHandle: number;

    private hadWindowHandle: boolean = false;

    constructor(parentId: string, id: string, style: number) {
        super(parentId, id, style);
        this.$thisNode = $(ACefNativeWindow.Template).attr({ id: this.id });
        this.$plugin = this.$thisNode.find("embed");
    }

    public setHandle(args: { handle: number }) {
        this.windowHandle = args.handle;
        if ($("#" + this.id).length !== 0) {//确保embed已经在页面上生成，否则调用不了setHandle
            if (this.windowHandle === 0 || this.windowHandle) {
                try {
                    this.$plugin[0].setHandle(this.windowHandle);
                    this.hadWindowHandle = true;
                } catch (e) {
                    console.error(e);
                }
            }
        }
    }

    // 注意，本方法允许被调用多次，需要控制好资源创建和销毁！！！
    public postLayout() {
        super.postLayout();
        if ((this.windowHandle === 0 || this.windowHandle) && !this.hadWindowHandle) {
            if ($("#" + this.id).length !== 0) {
                // 稍等片刻再设置，否则会报各种奇怪的错误
                setTimeout(this.setHandle({ handle: this.windowHandle }), 300);
            } else {
                // 有可能调用了postLayout之后$thisNode还没append到页面，最多再重复设置5次
                let count = 0;
                let own = this;
                let func = function () {
                    if ($("#" + own.id).length !== 0) {
                        own.setHandle({ handle: own.windowHandle });
                    } else {
                        count++;
                        if (count < 5) {
                            setTimeout(func(), 500);
                        }
                    }
                };
                setTimeout(func, 300);
            }

        }
    }


}