import { LitElement, html, css } from 'lit-element'
import { notifyChangeEvent } from '@things-factory/utils'
import '@material/mwc-button'

import { getRobotArmPose, robotArmTaskMoveTo } from './robot-arm-control-api'

const LABELS = ['x', 'y', 'z', 'u', 'v', 'w']

export class RobotArmPoseListItem extends LitElement {
  static get properties() {
    return {
      value: Object,
      connection: String,
      showInputs: Boolean
    }
  }

  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: row;
      }

      [inputs] {
        flex: 1;

        display: flex;
        flex-direction: column;
        margin-bottom: 5px;
        position: relative;
        margin-right: -3px;
      }

      [pose-values] {
        flex: 1;

        display: grid;
        grid-template-columns: repeat(3, 25px 1fr);
        grid-gap: 4px 4px;
        margin-top: 5px;
        padding: 9px;
        background-color: #f6f6f6;
        border-radius: 4px;
      }
      input {
        padding: 4px 9px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        border-radius: 4px;
        font: normal var(--fontsize-default) var(--theme-font);
      }
      [pose-values] label {
        font-size: 14px;
        line-height: 2.3;
        color: var(--secondary-text-color);
        font-weight: bold;
        text-align: right;
      }
      [pose-values] input {
        min-width: 50px;
      }
      mwc-icon-button {
        --mdc-icon-button-size: 32px;
        --mdc-icon-size: 18px;
        max-height: 32px;
        background-color: #f6f6f6;
        border: 1px solid rgba(0, 0, 0, 0.2);
        margin-right: -1px;
        color: #747474;
      }
      mwc-icon-button:last-child {
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
        position: relative;
        margin-right: -2px;
      }
    `
  }

  render() {
    var { name, pose } = this.value || {}

    return html`
      <div inputs>
        <input
          id="name"
          type="text"
          .value=${name || ''}
          placeholder=${"Key-in pose's name"}
          @change=${e => this.onChangeName(e)}
        />
        ${this.showInputs
          ? html`
              <div @change=${e => this.onChangePose(e)} pose-values>
                ${LABELS.map(
                  key => html`
                    <label for=${key}>${key.toUpperCase()}</label>
                    <input id=${key} type="number" .value=${(pose && pose[key]) || 0} placeholder=${key} />
                  `
                )}
              </div>
            `
          : html``}
      </div>

      <mwc-icon-button dense @click=${e => (this.showInputs = !this.showInputs)} icon="expand_more"></mwc-icon-button>
      <mwc-icon-button dense @click=${e => this.onClickSet(e)} icon="edit"></mwc-icon-button>
      <mwc-icon-button dense @click=${e => this.onClickMove(e)} icon="my_location"></mwc-icon-button>
    `
  }

  async setByCurrentPose() {
    this.value = {
      ...this.value,
      pose: await getRobotArmPose(this.connection)
    }
    notifyChangeEvent(this, this.value)

    return this.value
  }

  setByInputs() {
    var inputs = this.renderRoot.querySelectorAll('[pose-values] input')
    var values = Array.from(inputs).map(input => input.value)

    this.value = {
      ...this.value,
      pose: LABELS.reduce((sum, key, idx) => {
        sum[key] = values[idx]
        return sum
      }, {})
    }

    notifyChangeEvent(this, this.value)

    return this.value
  }

  onChangeName(e) {
    e.stopPropagation()

    this.value = {
      ...this.value,
      name: e.target.value
    }

    notifyChangeEvent(this, this.value)
  }

  onChangePose(e) {
    e.stopPropagation()

    this.setByInputs()
  }

  async onClickSet(e) {
    // TODO 세팅되는 동안 버튼을 깜박임.
    await this.setByCurrentPose()
  }

  async onClickMove(e) {
    const { pose } = this.value || {}

    // TODO 움직이는 동안 버튼을 깜박임.
    return this.connection && pose && (await robotArmTaskMoveTo(this.connection, pose))
  }
}

customElements.define('robot-arm-pose-list-item', RobotArmPoseListItem)
