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 { privileged } from '@things-factory/auth-base/dist-client'
import { GroupBarStyles } from './group-bar-styles'

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

  @property({ type: Array }) groups?: any[]
  @property({ type: String }) groupId?: string
  @property({ type: String }) targetPage?: string

  private __sb?: ScrollBooster

  render() {
    return html`
      <ul>
        <li ?active=${!this.groupId}>
          <a href=${this.targetPage || ''}><md-icon>dashboard</md-icon></a>
        </li>

        <li ?active=${this.groupId === 'favor'}>
          <a href="${this.targetPage}/favor"><md-icon>star</md-icon></a>
        </li>

        ${privileged(
          { privilege: 'mutation', category: 'board' },
          html`<li ?active=${this.groupId === 'mywork'}>
            <a href="${this.targetPage}/mywork"><md-icon>engineering</md-icon></a>
          </li>`
        )}
        ${(this.groups || []).map(
          group => html`
            <li ?active=${this.groupId === group.id} @long-press=${e => this.infoGroup(group.id)}>
              <a href=${`${this.targetPage}/${group.id}`}>${group.name}</a>
            </li>
          `
        )}

        <li padding></li>

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

  infoGroup(groupId?: string) {
    this.dispatchEvent(
      new CustomEvent('info-group', {
        detail: groupId
      })
    )
  }

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

    e.preventDefault()
  }

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