import * as Rx from 'rx/dist/rx.all';
import { Breakpoints } from './config/Breakpoints';
import { Utils } from './Utils';

const DEBOUNCE_DELAY = 200;

class ScreenSizeDetection {

  private subject: Rx.BehaviorSubject;

  public screensize: string;
  public mocksize: string;

  constructor() {
    this.screensize = this.calculate();
    this.subject = new Rx.BehaviorSubject(this.screensize);
    this.addEventListeners();
  }

  public get(): Rx.BehaviorSubject {
    return this.subject;
  }

  public calculate(): string {
    let deviceWidth = this.mocksize || window.innerWidth;
    let sizes = Object.keys(Breakpoints);
    for (let i = 0; i < sizes.length; i++) {
      if (i === sizes.length - 1) {
        return sizes[i]
      };
      let current = Breakpoints[sizes[i]];
      let next = Breakpoints[sizes[i + 1]];
      if (deviceWidth > current && deviceWidth <= next) {
        return sizes[i];
      }
    }
  }

  public resizeHandler(): void {
    let screensize = this.calculate();
    if (screensize !== this.screensize) {
      this.screensize = screensize;
      console.log('screen', this.screensize);
      this.subject.onNext(this.screensize);
    };
  }

  private addEventListeners(): void {
    window.addEventListener('resize', Utils.debounce(() => {
      this.resizeHandler();
    }, DEBOUNCE_DELAY), false);
  }
}

export default new ScreenSizeDetection;
