import { IViewAbility } from "./IViewAbility";

export class Geometry implements IViewAbility {
    private inFrame: boolean;
    private ad: any;
    constructor(el: HTMLElement) {
        this.inFrame = self === top ? false : true;
        this.ad = el;
    }
    public isSupported(cb?: Function): boolean {
        let phostName: string;
        let status = true;
        try {
            phostName = window.parent.location.hostname;
        } catch (error) {
            status = false;
        }
        if (typeof this.ad === "undefined" || this.ad == null || window.location.hostname !== phostName) {
            status = false;
        }
        if (typeof cb === "function") {
            cb(status);
        }
        return status;
    }

    public isView = () => {
        if (!this.isSupported()) {
            return false;
        }
        let el = this.ad;
        let top = el.offsetTop;
        let left = el.offsetLeft;
        let width = el.offsetWidth;
        let height = el.offsetHeight;

        while (el.offsetParent) {
            el = el.offsetParent;
            top += el.offsetTop;
            left += el.offsetLeft;
        }
        let current = self;

        if (this.inFrame) {
            top += current.pageYOffset;
            left += current.pageXOffset;
            while (current.parent) {
                current = current.parent;
                if (current === window.top) {
                    break;
                }
            }
        }
        return (
            top >= current.pageYOffset &&
            left >= current.pageXOffset &&
            top + height <= (current.pageYOffset + current.innerHeight) &&
            left + width <= (current.pageXOffset + current.innerWidth)
        );
    }
}
