import { Utility } from '../../core/utility';
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;

  constructor(element) {
    if (!element) {
      throw new Error('CourseTeaser utility cannot be setup without an element!');
    }
    if (element.classList.contains(COURSE_TEASER_INITIALIZED_CLASS)) {
      return false;
    }
    this._element = element;
    element.addEventListener('click', e => this._onToggleExpand(e));
  }

  _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);
    }
  }

}
