import '@things-factory/grist-ui'

import { css, html, LitElement } from 'lit-element'

import { SingleColumnFormStyles } from '@things-factory/form-ui'
import { i18next, localize } from '@things-factory/i18n-base'

class DispatcherVerificationPopup extends localize(i18next)(LitElement) {
  static get styles() {
    return [
      SingleColumnFormStyles,
      css`
        :host {
          padding: 10px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .button-container {
          padding: var(--button-container-padding);
          margin: var(--button-container-margin);
          text-align: var(--button-container-align);
          background-color: var(--button-container-background);
          height: var(--button-container-height);
        }
      `
    ]
  }

  get dispatchmentForm() {
    return this.shadowRoot.querySelector('form[name=dispatchmentForm]')
  }

  render() {
    return html`
      <form name="dispatchmentForm" class="single-column-form">
        <fieldset>
          <label>${i18next.t('label.dispatcher_name')}</label>
          <input name="dispatcherName" required />

          <label>${i18next.t('label.dispatcher_identity')}</label>
          <input name="dispatcherIdentity" required />
        </fieldset>
      </form>
      <div class="button-container">
        <mwc-button
          @click="${this._updateManifestDispatchement.bind(this)}"
          label="${`${i18next.t('button.confirm')}`}"
          raised
        ></mwc-button>
      </div>
    `
  }

  _updateManifestDispatchement() {
    if (this.dispatchmentForm.checkValidity()) {
      let dispatchment = this._serializeForm(this.dispatchmentForm)
      this.dispatchEvent(
        new CustomEvent('dispatch', {
          detail: {
            dispatcherName: dispatchment.dispatcherName,
            dispatcherIdentity: dispatchment.dispatcherIdentity
          }
        })
      )
      history.back()
    } else {
      this._showToast({ message: i18next.t('text.form_has_invalid_input') })
    }
  }

  _serializeForm(form) {
    let obj = {}
    Array.from(form.querySelectorAll('input')).forEach(field => {
      if (!field.hasAttribute('hidden') && field.value) {
        obj[field.name] = field.type === 'checkbox' ? field.checked : field.value
      }
    })

    return obj
  }

  _showToast({ type, message }) {
    document.dispatchEvent(
      new CustomEvent('notify', {
        detail: {
          type,
          message,
          option: { timer: 1000 }
        }
      })
    )
  }
}

window.customElements.define('dispatcher-verification-popup', DispatcherVerificationPopup)
