import { Utility } from '../../core/utility';
import './show-hide.scss';

const SHOW_HIDE_LOCAL_STORAGE_KEY = 'SHOW_HIDE';
const SHOW_HIDE_INITIALIZED_CLASS = 'show-hide--initialized';
const SHOW_HIDE_COLLAPSED_CLASS = 'show-hide--collapsed';
const SHOW_HIDE_TOGGLE_CLASS = 'show-hide__toggle';
const SHOW_HIDE_TOGGLE_RIGHT_CLASS = 'show-hide__toggle--right';

@Utility({
  selector: '[uw-show-hide]',
})
export class ShowHide {

  _showHideId;
  _element;

  constructor(element) {
    if (!element) {
      throw new Error('ShowHide utility cannot be setup without an element!');
    }

    this._element = element;

    if (this._element.classList.contains(SHOW_HIDE_INITIALIZED_CLASS)) {
      return false;
    }

    // register click listener
    this._addClickListener();

    // param showHideId
    if (this._element.dataset.showHideId) {
      this._showHideId = this._element.dataset.showHideId;
    }

    // param showHideCollapsed
    let collapsed = false;
    if (this._element.dataset.showHideCollapsed !== undefined) {
      collapsed = true;
    }

    if (this._showHideId) {
      let localStorageCollapsed = this._getLocalStorage()[this._showHideId];
      if (typeof localStorageCollapsed !== 'undefined') {
        collapsed = localStorageCollapsed;
      }
    }
    this._element.parentElement.classList.toggle(SHOW_HIDE_COLLAPSED_CLASS, collapsed);

    // param showHideAlign
    const alignment = this._element.dataset.showHideAlign;
    if (alignment === 'right') {
      this._element.classList.add(SHOW_HIDE_TOGGLE_RIGHT_CLASS);
    }

    // mark as initialized
    this._element.classList.add(SHOW_HIDE_INITIALIZED_CLASS, SHOW_HIDE_TOGGLE_CLASS);
  }

  destroy() {
    this._element.removeEventListener('click', this._clickHandler);
  }

  _addClickListener() {
    this._element.addEventListener('click', this._clickHandler);
  }

  _clickHandler = () => {
    const newState = this._element.parentElement.classList.toggle(SHOW_HIDE_COLLAPSED_CLASS);

    if (this._showHideId) {
      this._setLocalStorage(this._showHideId, newState);
    }
  }

  // maybe move these to a LocalStorageHelper?
  _setLocalStorage(id, state) {
    const lsData = this._getLocalStorage();
    lsData[id] = state;
    window.localStorage.setItem(SHOW_HIDE_LOCAL_STORAGE_KEY, JSON.stringify(lsData));
  }

  _getLocalStorage() {
    return JSON.parse(window.localStorage.getItem(SHOW_HIDE_LOCAL_STORAGE_KEY)) || {};
  }
}
