import _ from 'underscore';

class Cache {
  static STORAGE_KEY = 'frontpanel-data-cache';

  dataHandlerMap: { [key: string]: Function } = {};

  constructor() {
    _.bindAll(this, 'handleComponentLoad');

    if (!localStorage[Cache.STORAGE_KEY]) {
      localStorage[Cache.STORAGE_KEY] = '{}'
    }
  }

  initEvent() {
    if ((window as any).ee) {
      (window as any).ee.on('front-component-loaded', this.handleComponentLoad);
    }
  }

  addHandler(key: string = '', callback: Function) {
    if (key) {
      this.dataHandlerMap[key] = callback;
    }
  }

  get(key: string = '') {
    if (!key) {
      return {};
    }

    const cache = this.load();

    return cache[key] || {};
  }

  handleComponentLoad(componentId: string) {
    const callback = this.dataHandlerMap[componentId];
    if (_.isFunction(this.dataHandlerMap[componentId])) {
      const data = this.get(componentId);
      if (!_.isEmpty(data)) {
        callback(data);
      }
    }
  }

  load() {
    return JSON.parse(localStorage[Cache.STORAGE_KEY]);
  }

  save(cache: any = {}) {
    localStorage[Cache.STORAGE_KEY] = JSON.stringify(cache);
  }

  set(key: string = '', data: any = {}) {
    const cache = this.load();

    cache[key] = data;

    this.save(cache);
  }
}

export default new Cache();