import uuidv4 from "../../func/utils/uuidv4";
import ClassName from "../../container/ClassName";
import { Injectable } from "../../container/Injectable";

@ClassName('WindowActiveState')
@Injectable()
export default class WindowActiveState {
    private isFocus = false;
    private uuid = uuidv4();

    constructor() {
        if (self !== top) return null;
        localStorage.setItem('whuuid', this.uuid);
        document.addEventListener('visibilitychange',
            () => (document.visibilityState !== 'hidden') && (localStorage.setItem('whuuid', this.uuid))
        );
        addEventListener('focus', () => this.isFocus = true);
        addEventListener('blur', () => this.isFocus = false);
    }

    // 当前实例是否激活
    get(): boolean {
        // 当前窗口获得了焦点 优先级最高
        if (this.isFocus) return true;
        // 可视性
        if (!document.hidden) return true;
        // 全部在后台，使用唯一id判断
        return this.uuid === localStorage.getItem('whuuid')
    }
}
