// 'use strict'
/* global m */

import { byKeyToByLang, makeFmt } from './translate.js'

// TODO: ugly shit
const urlParams = new URLSearchParams(window.location.search)
const QUICK = urlParams.get('quick')
const Q = urlParams.get('q')

// TODO: move this to some common module
const myNormalize = x => x.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')

const handleKeyUp = (e, d, vnode) => {
  if (e.keyCode === 13) {
    const v = e.target.value.replace(',', '.')
    vnode.state.v = v
    console.log('SUBMIT', d.k, d.subk, v)
    m.request({ url: './validate_and_save/' + d.k + '/' + d.subk + '/' + v })
      .then(data => {
        console.log('SAVED', data)
        // this.ret = data["ret"];  // TODO: ugly
        if (!data.err) {
          vnode.attrs.data.v = data.ret // TODO: ugly
          vnode.state.color = '#aaffaa'
        } else {
          vnode.state.color = '#ffaaaa'
        }
        setTimeout(() => {
          vnode.state.color = null
          m.redraw()
        }, 2000)
      })
      .catch(err => {
        console.log('SAVE ERR', err)
      })
  } else {
    vnode.state.v = e.target.value // TODO: ugly ugly shit
  }
}

// TODO: find a better name
const genFiltStr = (d) => {
  return d.k + '.' + d.subk + ' ' + d._human_name + ' ' + d._cap + ' ' + d._material_name
}

const ParamListItem = {
  oninit: vnode => {
    vnode.state.display = 'none'
  },
  view: vnode => {
    const filt = vnode.attrs.filt.split(' ')
    const d = vnode.attrs.data
    const fmt = vnode.attrs.fmt
    const filteredList = d.items.filter(x => filt.every(xx => myNormalize(fmt(genFiltStr(x))).indexOf(myNormalize(xx)) !== -1))
    if (filteredList.length === 0) {
      return null
    }
    const title = fmt(d.title) + (d.material_name != null ? ' (' + d.material_name + ')' : '')
    const display = vnode.attrs.filt ? 'flex' : vnode.state.display
    const icon = display === 'flex' ? 'fa-angle-up' : 'fa-angle-down'
    return m('.' + d.material_type, { border: 1 }, [
      m('.head.' + d.material_type, { onclick: _e => { vnode.state.display = (vnode.state.display === 'none' ? 'flex' : 'none') } }, [
        m('.title', { title: d.k }, title),
        m('.chevron.i.fa ' + icon)
      ]),
      m('.bTable', { style: { display } }, [
        m('table', filteredList.map(x => m(ParamListSubItem, { key: x.subk, data: x, fmt })))
      ])
    ])
  }
}

const ParamListSubItem = {
  view: vnode => {
    const d = vnode.attrs.data
    const fmt = vnode.attrs.fmt
    const v = (vnode.state.v != null ? vnode.state.v : vnode.attrs.data.v)
    const color = (vnode.state.color != null ? vnode.state.color : (vnode.state.v != null && vnode.state.v != vnode.attrs.data.v ? '#ffffaa' : null)) // eslint-disable-line eqeqeq
    return m('tr', [
      m('td.rightTD', { title: d.tooltip }, fmt(d.title)),
      m('td',
        m('input', {
          size: 5,
          title: d.unit,
          style: { backgroundColor: color },
          value: v,
          onkeyup: e => handleKeyUp(e, d, vnode)
        })
      ),
      m('td.hintTD', d.limit_str)
    ])
  }
}

const ParamList = {
  oninit: vnode => {
    console.log('init')
    vnode.state.list = []
    m.request({
      url: './get_fill_data',
      method: 'GET'
    }).then(data => {
      console.log('GOT', data)
      vnode.state.list = data
    })
  },
  view: vnode => {
    const d = vnode.attrs
    const fmt = vnode.attrs.fmt
    return m('', [
      m('', vnode.state.list.map(x => m(ParamListItem, { key: x.k, filt: d.filt, data: x, fmt })))
    ])
  }
}

const ParamQuickList = {
  oninit: vnode => {
    console.log('init quick')
    vnode.state.list = []
    m.request({
      url: './get_fill_data_quick',
      method: 'GET'
    }).then(data => {
      console.log('GOT', data)
      vnode.state.list = data
    })
  },
  view: vnode => {
    // const d = vnode.attrs;
    const fmt = vnode.attrs.fmt
    return m('table', vnode.state.list.map(x => m(ParamQuickListItem, { key: x.title, data: x, fmt })))
  }
}

const ParamQuickListItem = {
  view: vnode => {
    const d = vnode.attrs.data
    const fmt = vnode.attrs.fmt
    return [
      m('tr.' + d.material_type, [
        m('td.' + d.material_type, { colspan: 4 }, fmt(d.title))
      ]),
      d.items.map(x => m(ParamQuickListSubItem, { key: x.k, data: x, fmt }))
    ]
  }
}

const ParamQuickListSubItem = {
  view: vnode => {
    const d = vnode.attrs.data
    const v = (vnode.state.v != null ? vnode.state.v : vnode.attrs.data.v)
    const color = (vnode.state.color != null ? vnode.state.color : (vnode.state.v != null && vnode.state.v != vnode.attrs.data.v ? '#ffffaa' : null)) // eslint-disable-line eqeqeq
    return m('tr', [
      m('td', d.silo_num),
      m('td.tdName', d.material_name),
      m('td',
        m('input.inputTD', {
          size: 5,
          style: { backgroundColor: color },
          value: v,
          onkeyup: e => handleKeyUp(e, d, vnode)
        })
      ),
      m('td', '[' + d.unit + ']')
    ])
  }
}

const Main = {
  oninit: vnode => {
    vnode.state.filt = (Q || '')
  },
  oncreate: _vnode => {
    // TODO: hacky shit - solve better
    document.getElementById('theInput').focus()
  },
  view: vnode => {
    const fmt = vnode.attrs.fmt
    if (QUICK) {
      return m(ParamQuickList, { fmt })
    }
    const color = vnode.state.filt ? '#baffba' : 'white'
    return m('', [
      m('.searchLine.sticky', [
        m('', fmt('{search} ')),
        m('input#theInput', {
          style: { backgroundColor: color, marginLeft: '0.5vw' },
          value: vnode.state.filt,
          oninput: e => {
            console.log('INPUT', e.target.value)
            vnode.state.filt = e.target.value
          }
        })
      ]),
      m(ParamList, { filt: vnode.state.filt, fmt })
    ])
  }
}

// TODO: cut-n-pasted from pymanager
const LanguageMain = {
  oninit: vnode => {
    vnode.state.lang = urlParams.get('lang') || 'cs'
    console.log('lang is', vnode.state.lang)
    vnode.state.byLangDict = {}
    m.request('./captions').then(data => {
      console.log('got lang', data)
      vnode.state.byLangDict = byKeyToByLang(data)
      vnode.state.fmt = makeFmt(vnode.state.lang, vnode.state.byLangDict)
    })
  },
  view: vnode => {
    if (!vnode.state.fmt) {
      return m('Loading...')
    }
    return m(Main, { fmt: vnode.state.fmt })
  }
}

m.mount(document.getElementById('content'), LanguageMain)
