import localStorageService from '@/service/localStorage.service';
import { isApp } from '@/service/validation.service';
export default {
  data() {
    return {
      visibilityChange: null,
      visibilityHidden: null
    };
  },
  mounted() {
    localStorageService.remove('invoiceRefresh');
    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) {
        const refresh = localStorageService.get('invoiceRefresh');
        if (refresh) {
          this.refreshChange && this.refreshChange();
          localStorageService.remove('invoiceRefresh');
          return;
        }
      }
    }
  }
};
