import * as  config from "./../common-var/config";
import { IViewAbility } from "./IViewAbility";
declare var window: any;
declare var $sf: any;
export class SafeFrame implements IViewAbility {

    private extern: any;
    private ad: HTMLElement;
    private inView = false;
    constructor(el: HTMLElement) {
        this.ad = el;
        if (typeof $sf !== "undefined" || typeof window.extern !== "undefined") {
            this.extern = $sf.ext;
        }
        if (this.isSupported()) {
            this.register();
        }
    }
    public isSupported = (cb?: Function): boolean => {
        let status = true;
        if (typeof this.extern === "undefined") {
            status = false;
        }
        if (typeof this.ad === "undefined") {
            status = false;
        }
        if (typeof cb === "function") {
            cb(status);
        }
        return status;
    }

    public statusUpdate = (status: string, data: string) => {
        if (status === "geom-update") {
            this.updateInView();
        }
    }
    public isView = () => {
        return this.inView;
    }
    public updateInView = () => {
        let ratio = this.ad.scrollWidth * this.ad.scrollHeight >=
            config.largeSize ? config.largeReduce : config.defaultReduce;
        this.inView = this.extern.inViewPercentage() >= ratio * 100 ? true : false;
    }
    public register = () => {
        if (this.extern) {
            try {
                this.extern.register(this.ad.scrollWidth, this.ad.scrollHeight, this.statusUpdate);
            } catch (e) {
                // tslint:disable-next-line:no-console
                console.log("Exception or no safeframes available: " + e.message);
            }
        }
    }
}
