import '@things-factory/grist-ui'

import {
  css,
  html,
  LitElement
} from 'lit-element'
import { connect } from 'pwa-helpers/connect-mixin'

import { DirectPrinter } from '@things-factory/barcode-base'
import {
  i18next,
  localize
} from '@things-factory/i18n-base'
import { store } from '@things-factory/shell'
import { isMobileDevice } from '@things-factory/utils'

import { ITEM_LABEL_SETTING_KEY } from '../constants'

class ItemLabelPopup extends connect(store)(localize(i18next)(LitElement)) {
  static get properties() {
    return {
      config: Object,
      data: Object,
      items: Object,
      _itemLabel: Object
    }
  }

  static get styles() {
    return [
      css`
        :host {
          padding: 10px;
          display: flex;
          flex-direction: column;
          overflow-x: overlay;
          background-color: var(--main-section-background-color);
        }
        .grist {
          background-color: var(--main-section-background-color);
          display: flex;
          flex-direction: column;
          flex: 1;
          overflow-y: auto;
        }
        data-grist {
          overflow-y: hidden;
          flex: 1;
        }
        .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);
        }
      `
    ]
  }

  firstUpdated() {
    this.config = {
      pagination: { infinite: true },
      rows: { selectable: { multiple: true }, appendable: false },
      list: { fields: ['batchId', 'sku', 'printQty'] },
      columns: [
        { type: 'gutter', gutterName: 'sequence' },
        { type: 'gutter', gutterName: 'row-selector', multiple: true },
        {
          type: 'string',
          name: 'batchId',
          header: i18next.t('field.batch_no'),
          width: 150
        },
        {
          type: 'string',
          name: 'sku',
          header: i18next.t('field.sku'),
          width: 80
        },
        {
          type: 'object',
          name: 'product',
          header: i18next.t('field.product'),
          width: 250
        },
        {
          type: 'string',
          name: 'roNo',
          header: i18next.t('field.ro_no'),
          width: 250
        },
        {
          type: 'integer',
          name: 'printQty',
          header: i18next.t('field.print_no'),
          record: { editable: true },
          width: 80
        }
      ]
    }
  }

  get dataGrist() {
    return this.shadowRoot.querySelector('data-grist')
  }

  render() {
    return html`
      <div class="grist">
        <data-grist
          id="grist"
          .mode=${isMobileDevice() ? 'LIST' : 'GRID'}
          .config=${this.config}
          .data="${this.data}"
        ></data-grist>
      </div>

      <div class="button-container">
        <mwc-button raised @click="${this._printLabel.bind(this)}" label="${i18next.t('button.print')}"></mwc-button>
      </div>
    `
  }

  updated(changeProps) {
    if (changeProps.has('items')) {
      if (this.items && this.items.records && this.items.records.length) {
        this.data = {
          records: this.items.records
            .map(record => ({ ...record, startSeq: 1 }))
            .sort((a, b) => a.product.sku.localeCompare(b.product.sku))
        }
      }
    }
  }

  async _printLabel() {
    try {
      let itemId = this._itemLabel && this._itemLabel.id

      let _targetRows = this._validate()

      for (let record of _targetRows) {
        for (let i = 0; i < record.printQty; i++) {
          let searchParams = new URLSearchParams()

          searchParams.append('attentionTo', record.attentionTo)
          searchParams.append('attentionCompany', record.attentionCompany)
          searchParams.append('sku', record.sku)
          searchParams.append('location', record.location)
          searchParams.append('city', record.city)
          searchParams.append('refNo', record.refNo)
          searchParams.append('releaseQty', record.releaseQty)
          searchParams.append('counter', `${i + 1} / ${record.printQty}`)
          searchParams.append('roNo', record.roNo)
          if (typeof record.releaseDate === 'string') {
            let date = new Date(record.releaseDate)
            let day = date.getDate()
            let month = date.getMonth() + 1
            let year = date.getFullYear()

            let formattedDate = `${day.toString().padStart(2, '0')}/${month.toString().padStart(2, '0')}/${year}`

            searchParams.append('releaseDate', formattedDate)
          }

          try {
            const response = await fetch(`label-command/${itemId}?${searchParams.toString()}`, {
              method: 'GET'
            })

          if (response.status !== 200) {
            throw `Error : Can't get label command from server (response: ${response.status})`
          }

          let command = await response.text()

          if (!this.printer) {
            this.printer = new DirectPrinter()
          }

            await this.printer.print(command)
          } catch (ex) {
            delete this.printer
            throw ex
          }
        }
      }
    } catch (e) {
      this._showToast(e)
    }
  }

  _validate() {
    let _targetRows = this.dataGrist.selected.length > 0 ? this.dataGrist.selected : this.dataGrist.dirtyData.records
    if (!_targetRows.every(row => row.printQty)) throw new Error(i18next.t('text.print_qty_is_empty'))
    return _targetRows
  }

  stateChanged(state) {
    let itemLabelSetting = state.dashboard[ITEM_LABEL_SETTING_KEY]
    this._itemLabel = (itemLabelSetting && itemLabelSetting.board) || {}
  }

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

window.customElements.define('item-label-popup', ItemLabelPopup)
