import '@material/web/icon/icon.js'

import { html, LitElement } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import ScrollBooster from 'scrollbooster'

import { longpressable } from '@operato/utils'
import { GroupBarStyles } from './group-bar-styles'

@customElement('play-group-bar')
export default class PlayGroupBar extends LitElement {
  static styles = [GroupBarStyles]

  @property({ type: Array }) groups: { id: string; name: string }[] = []
  @property({ type: String }) groupId: string = ''
  @property({ type: String, attribute: 'target-page' }) targetPage: string = ''

  private __sb?: ScrollBooster

  render() {
    return html`
      <ul>
        ${(this.groups || []).map(
          group => html`
            <li ?active=${this.groupId === group.id} @long-press=${e => this._infoGroup(group)}>
              <a href=${`${this.targetPage}/${group.id}`}>${group.name}</a>
            </li>
          `
        )}

        <li padding>&nbsp;</li>

        <li add>
          <md-icon @click=${e => this._infoGroup()}>add</md-icon>
        </li>
      </ul>
    `
  }

  _infoGroup(group?: { id: string; name: string }) {
    this.dispatchEvent(
      new CustomEvent('info-play-group', {
        detail: group
      })
    )
  }

  _onWheelEvent(e) {
    var delta = Math.max(-1, Math.min(1, e.wheelDelta || -e.detail))
    this.scrollLeft -= delta * 40

    e.preventDefault()
  }

  _onClickAdd(e) {
    // TODO Implements
  }

  updated(change) {
    if (change.has('groups')) {
      /* groups가 바뀔 때마다, contents의 폭이 달라지므로, 다시 폭을 계산해준다. */
      this.__sb && this.__sb.updateMetrics()
    }

    if (change.has('groupId')) {
      var active = this.renderRoot.querySelector('li[active]')
      active && active.scrollIntoView()
    }
  }

  firstUpdated() {
    var scrollTarget = this.renderRoot.querySelector('ul')

    /* long-press */
    longpressable(scrollTarget!)

    scrollTarget!.addEventListener('mousewheel', this._onWheelEvent.bind(this), false)

    this.__sb = new ScrollBooster({
      viewport: this,
      content: scrollTarget,
      mode: 'x',
      onUpdate: data => {
        this.scrollLeft = data.position.x
      }
    })
  }
}
