import { Utility } from '../../core/utility';
import { EventManager, EventWrapper, EVENT_TYPE } from '../../lib/event-manager/event-manager';
import './course-teaser.sass';

const COURSE_TEASER_INITIALIZED_CLASS = 'course-teaser--initialized';

const COURSE_TEASER_EXPANDED_CLASS = 'course-teaser__expanded';
const COURSE_TEASER_CHEVRON_CLASS = 'course-teaser__chevron';

@Utility({
  selector: '[uw-course-teaser]:not(.course-teaser__not-expandable)',
})
export class CourseTeaser {

  _element;
  _eventManager

  constructor(element) {
    if (!element) {
      throw new Error('CourseTeaser utility cannot be setup without an element!');
    }
    this._eventManager = new EventManager();
    if (element.classList.contains(COURSE_TEASER_INITIALIZED_CLASS)) {
      return false;
    }
    this._element = element;
    const clickHandler =  e => this._onToggleExpand(e);
    const clickEvent = new EventWrapper(EVENT_TYPE.CLICK, clickHandler.bind(this), element);
    this._eventManager.registerNewListener(clickEvent);
  }

  destroy() {
    this._eventManager.removeAllEventListenersFromUtil();
    if(this._element.classList.contains(COURSE_TEASER_EXPANDED_CLASS)) {
      this._element.classList.remove(COURSE_TEASER_EXPANDED_CLASS);
    }
    if (this._element.classList.contains(COURSE_TEASER_INITIALIZED_CLASS)) {
      this._element.classList.remove(COURSE_TEASER_INITIALIZED_CLASS);
    }
  }

  _onToggleExpand(event) {
    const isLink = event.target.tagName.toLowerCase() === 'a';
    const isChevron = event.target.classList.contains(COURSE_TEASER_CHEVRON_CLASS);
    const isExpanded = this._element.classList.contains(COURSE_TEASER_EXPANDED_CLASS);

    if ((!isExpanded && !isLink) || isChevron) {
      this._element.classList.toggle(COURSE_TEASER_EXPANDED_CLASS);
    }
  }

}
