import { getOption, reloadSettings } from "@/helpers/common";

export const visibility = {
    data() {
        return {
            checkFocusTimer: 0,
            hidden: 'hidden',
            visibilityChange: 'visibilitychange',
            hasFocus: false
        }
    },
    components: {
    },
    computed: {
        account() {
            return getOption('account');
        }
    },
    mounted() {
        this.initialize();
    },
    beforeDestroy() {
        document.removeEventListener(this.visibilityChange, this.handleVisibilityChange)
    },
    methods: {
        initialize() {
            if (this.account.connected === true) return;
            if (typeof document.hidden !== 'undefined') {
                this.hidden = 'hidden';
                this.visibilityChange = 'visibilitychange';
            } else if (typeof document.msHidden !== 'undefined') { // IE10.
                this.hidden = 'msHidden';
                this.visibilityChange = 'msvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') { // Android.
                this.hidden = 'webkitHidden';
                this.visibilityChange = 'webkitvisibilitychange';
            }
            document.addEventListener(this.visibilityChange, this.handleVisibilityChange, false);
        },
        handleVisibilityChange() {
            if (!document[this.hidden]) {
                this.checkForScreenChange();
            }
        },
        async checkForScreenChange() {
            await reloadSettings();
            if (this.account.connected) {
                document.removeEventListener(this.visibilityChange, this.handleVisibilityChange)
                this.$router.redirectToDashboard(this.$route.name);
            }
        }
    },
}
