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

import {
  getRobotArmStatus,
  startTeachingMode,
  finishTeachingMode,
  robotArmTaskMoveTo,
  robotArmReset,
  robotArmGoHome
} from './robot-arm-control-api'

export class RobotArmController extends LitElement {
  static get styles() {
    return css`
      :host {
        display: flex;
        flex-direction: row;
      }
      mwc-button {
        --mdc-theme-primary: #fff;
        background-color: var(--secondary-color);
        border-radius: var(--border-radius);
        margin: 0 0 5px 5px;
        padding-bottom: 2px;
      }
      [modeSwitch] span {
        width: 16px;
        height: 16px;
        background-color: #efefef;
        border-radius: 10px;
        border-style: solid;
        border-color: #2b2e3a;
        border-width: 2px 30px 2px 2px;
        margin: 2px 0 0 7px;
      }
      [modeSwitch] span::before {
        content: 'off';
        position: relative;
        top: -5px;
        margin-left: 20px;
        font-size: 9px;
      }
      [modeSwitch][switchOn] span {
        background-color: #fff;
        border-color: #8bc34a;
        border-width: 2px 2px 2px 30px;
      }
      [modeSwitch][switchOn] span::before {
        content: 'on';
        margin-left: -40px;
        font-size: 10px;
        font-weight: bold;
      }
    `
  }

  static get properties() {
    return {
      connection: String,
      program: Array,
      teachingMode: Boolean
    }
  }

  render() {
    // TODO 움직이는 동안 버튼 깜박이기. 현재 (티칭)모드를 표현해주기.
    return html`
      <mwc-button
        dense
        label="Mode Change"
        @click=${e => this.changeTeachingMode()}
        modeSwitch
        ?switchOn=${this.teachingMode}
        ><span></span
      ></mwc-button>
      <mwc-button
        dense
        label="Reset"
        icon="published_with_changes"
        @click=${e => robotArmReset(this.connection)}
      ></mwc-button>
      <mwc-button dense label="Home" @click=${e => robotArmGoHome(this.connection)}></mwc-button>
      ${this.program
        ? html`<mwc-button
            dense
            label="Play"
            icon="play_circle_outline"
            @click=${e => this.playProgram()}
          ></mwc-button>`
        : html``}
    `
  }

  async firstUpdated() {
    if (this.connection) {
      const status = await getRobotArmStatus(this.connection)
      this.teachingMode = status?.teachingMode
    }
  }

  async playProgram() {
    for (let step of this.program || []) {
      await robotArmTaskMoveTo(this.connection, step)
    }
  }

  async changeTeachingMode() {
    const name = this.connection || ''
    const success = this.teachingMode ? await finishTeachingMode(name) : await startTeachingMode(name)

    if (success) {
      this.teachingMode = !this.teachingMode
    }
  }
}

customElements.define('robot-arm-controller', RobotArmController)
