import { debounce } from '../utils/debounce';
import { makeAutoObservable } from 'mobx';
/**
 * Breakpoint for min XS screen width
 */
export const MinScreenSizeXS = 0;
/**
 * Breakpoint for min S screen width
 */
export const MinScreenSizeS = 600;
/**
 * Breakpoint for min M screen width
 */
export const MinScreenSizeM = 960;
/**
 * Breakpoint for min L screen width
 */
export const MinScreenSizeL = 1280;
/**
 * Breakpoint for min XL screen width
 */
export const MinScreenSizeXL = 1920;
/**
 * Breakpoint for max XS screen width
 */
export const MaxScreenSizeXS = MinScreenSizeS - 1;
/**
 * Breakpoint for max S screen width
 */
export const MaxScreenSizeS = MinScreenSizeM - 1;
/**
 * Breakpoint for max M screen width
 */
export const MaxScreenSizeM = MinScreenSizeL - 1;
/**
 * Breakpoint for max L screen width
 */
export const MaxScreenSizeL = MinScreenSizeXL - 1;
/**
 * Breakpoint for max XL screen width
 */
export const MaxScreenSizeXL = undefined;

export class WindowSizeStore {
  windowWidth: number | null;
  screenWindow: any;
  windowHeight: number | null;
  panels: any;

  constructor() {
    this.windowWidth = null;
    this.windowHeight = null;
    this.screenWindow = null;
    this.setWindow();
    this.panels = {};
    makeAutoObservable(this);
  }

  get hasMinimalPortraitMobileWidth() {
    if (this.width === null) {
      return false;
    }
    return this.width <= MinScreenSizeS;
  }

  get width() {
    return this.windowWidth || 0;
  }

  get height() {
    return this.windowHeight || 0;
  }

  get panelSizes() {
    return this.panels;
  }

  setWindow = () => {
    if (typeof window === 'object') {
      this.screenWindow = window;
      this.handleWindowWidthChange();
      this.screenWindow.addEventListener(
        'resize',
        this.handleWindowWidthChange
      );
      this.screenWindow.addEventListener(
        'dragover',
        function (e: any) {
          // eslint-disable-next-line
          e = e || event;
          e.preventDefault();
        },
        false
      );
      this.screenWindow.addEventListener(
        'drop',
        function (e: any) {
          // eslint-disable-next-line
          e = e || event;
          e.preventDefault();
        },
        false
      );
    }
  };

  private handleWindowWidthChange = debounce(() => {
    const width = this.screenWindow.innerWidth;
    const height = this.screenWindow.innerHeight;
    this.setWindowWidth(width);
    this.setWindowHeight(height);
  }, 100);

  private setWindowWidth = (width: number) => {
    this.windowWidth = width;
  };

  private setWindowHeight = (height: number) => {
    this.windowHeight = height;
  };

  setAppPanels = (panels: string[]) => {
    panels.forEach((panel) => {
      this.panels[panel] = true;
    });
  };

  expandPanel = (panelId: string) => {
    this.panels[panelId] = !this.panels[panelId];
  };
}
