import localStorageService from '@/service/localStorage.service';
import { isApp } from '@/service/validation.service';
export default {
  data() {
    return {
      refreshKey: null,
      visibilityChange: null,
      visibilityHidden: null
    };
  },
  mounted() {
    this.refreshKey && localStorageService.remove(this.refreshKey);
    if (isApp) {
      this.pageVisibilityChange();
    }
  },
  beforeDestroy() {
    this.removePageVisibility();
  },
  methods: {
    getEvent() {
      let hidden = 'hidden';
      let visibilityChange = 'visibilitychange';
      if (typeof document.hidden !== 'undefined') {
        hidden = 'hidden';
        visibilityChange = 'visibilitychange';
      } else if (typeof document.webkitHidden !== 'undefined') {
        hidden = 'webkitHidden';
        visibilityChange = 'webkitvisibilitychange';
      }
      return { hidden, visibilityChange };
    },
    removePageVisibility() {
      window.removeEventListener(this.visibilityChange, this.handleVisibilityChange, false);
    },
    pageVisibilityChange() {
      const { visibilityChange, hidden } = this.getEvent();
      this.visibilityChange = visibilityChange;
      this.visibilityHidden = hidden;
      window.addEventListener(visibilityChange, this.handleVisibilityChange, false);
    },
    handleVisibilityChange() {
      const state = document[this.visibilityHidden];
      if (!state) {
        if (this.refreshKey) {
          if (localStorageService.get(this.refreshKey)) {
            this.refreshChange && this.refreshChange();
            return;
          }
        }
        this.refreshChange && this.refreshChange();
      }
    }
  }
};
