import '@operato/board/ox-board-selector.js'
import './board-renderer'

import { css, html } from 'lit'
import { customElement, property, query } from 'lit/decorators.js'

import { OxGristEditor } from '@operato/data-grist'
import { i18next } from '@operato/i18n'
import { openPopup } from '@operato/layout'

@customElement('board-editor')
export class BoardEditor extends OxGristEditor {
  static styles = [
    css`
      :host {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;

        box-sizing: border-box;

        width: 100%;
        height: 100%;

        border: 0;
        background-color: transparent;

        font: var(--grist-object-editor-font);
        color: var(--grist-object-editor-color);

        justify-content: inherit;
      }

      board-renderer {
        display: flex;
        flex: auto;

        justify-content: inherit;
      }
    `
  ]

  @property({ type: Object }) value: any
  @property({ type: Object }) column: any
  @property({ type: Object }) record: any
  @property({ type: Number }) row?: number

  popup

  render() {
    var { boardViewerPage } = this.column.record.options || {}
    return html` <board-renderer .value=${this.value} .boardViewerPage=${boardViewerPage}></board-renderer> `
  }

  async firstUpdated() {
    this.value = this.record[this.column.name]

    await this.updateComplete

    this.renderRoot.addEventListener('click', e => {
      e.stopPropagation()

      this.openSelector()
    })

    this.openSelector()
  }

  openSelector() {
    if (this.popup) {
      delete this.popup
    }

    /*
     * 기존 설정된 보드가 선택된 상태가 되게 하기 위해서는 selector에 value를 전달해줄 필요가 있음.
     * 주의. value는 object일 수도 있고, string일 수도 있다.
     * string인 경우에는 해당 보드의 id로 해석한다.
     */
    var value = this.value || {}

    var template = html`
      <ox-board-selector
        .creatable=${true}
        .value=${this.value}
        @board-selected=${async e => {
          var board = e.detail.board

          this.dispatchEvent(
            new CustomEvent('field-change', {
              bubbles: true,
              composed: true,
              detail: {
                before: this.value,
                after: this.column.type == 'board' ? board : board.id || '',
                record: this.record,
                column: this.column,
                row: this.row
              }
            })
          )

          this.popup && this.popup.close()
        }}
      ></ox-board-selector>
    `

    this.popup = openPopup(template, {
      backdrop: true,
      size: 'large',
      title: i18next.t('title.select board')
    })
  }
}
