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 RobotArmPoseInput extends LitElement {
  static get properties() {
    return {
      value: Object,
      connection: String
    }
  }

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

      [inputs] {
        flex: 1;

        display: flex;
        flex-direction: column;
      }

      [pose-values] {
        flex: 1;

        display: grid;
        grid-template-columns: repeat(3, 20px 1fr);
        grid-gap: 4px 4px;
        padding: 4px 0;
      }

      [pose-values] input {
        min-width: 50px;
      }
    `
  }

  render() {
    const pose = this.value || {}

    return html`
      <div inputs>
        <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>
      </div>

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

  async setByCurrentPose() {
    this.value = 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 = LABELS.reduce((sum, key, idx) => {
      sum[key] = values[idx]
      return sum
    }, {})

    notifyChangeEvent(this, this.value)

    return this.value
  }

  onChangePose(e) {
    e.stopPropagation()

    this.setByInputs()
  }

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

  async onClickMove(e) {
    const { connection, value } = this
    // TODO 움직이는 동안 버튼을 깜박임.
    return connection && value && (await robotArmTaskMoveTo(connection, value || {}))
  }
}

customElements.define('robot-arm-pose-input', RobotArmPoseInput)
