<template>
  <button
    type="button"
    id="logoutButton"
    v-on:click="send_orders()"
    >ayy lmao button</button>
  <HotTable
    ref="hotTableComponent"
    :settings="DefaultSettings()"
    ></HotTable>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { HotTable, HotColumn } from '@handsontable/vue3';

const storeRefs =  useStoreRef()
const {invs, activeTable, columns, tags, dirty, chars, currentSearch, orders} = storeRefs

const hotTableComponent = ref<any>(null)
const hott = ():Handsontable =>{
  return hotTableComponent.value.hotInstance as any
}
const session = storage.GetSession()
const api:LTOApi = getLTOState(LTOApiv0, session, useStoreRef())
const manager = new OrderSender(storeRefs)

const updateTable = ():TableRecipe | undefined => {
  if (invs.value.has(activeTable.value)) {
    const chardat = invs.value.get(activeTable.value)
    if (chardat) {
      const it = new InventoryTable(chardat, {
        columns: columns.value,
        tags: tags.value,
        accounts: Array.from(chars.value.keys()),
      } as InventoryTableOptions)
      const build = it.BuildTable()
      hott().updateSettings(build.settings)
      return build
    }
  }
  return undefined
}

watch(currentSearch, ()=>{
  filterTable()
})

const send_orders = () => {
  if(hott()) {
    const headers = hott().getColHeader()
    const dat = hott().getData()
    const idxNumber = headers.indexOf(Columns.MoveCount.displayName)
    const idxTarget = headers.indexOf(Columns.Move.displayName)
    const origin = activeTable
    const pending:OrderDetails[] = [];
    for(const row of dat) {
      try{
      const nm = Number(row[idxNumber].replace("x",""))
      const target = (row[idxTarget] as string).replaceAll("-","").trim()
      if(!isNaN(nm) && nm > 0 && target.length > 0){
        const info:OrderDetails = {
          item_uid: row[0].toString(),
          count: nm,
          origin_path: origin.value,
          target_path: target,
        }
        pending.push(info)
      }
      }catch(e){
      }
    }
    log.debug("OrderDetails", pending)
    for(const d of pending){
      const order = manager.send(d)
      order.tick(storeRefs, api)
    }
    saveStore();
  }
}


onMounted(()=>{
  window.setInterval(tick_orders, 1000)
})
const tick_orders = () => {
  if(orders && storeRefs && api){
    orders.value.tick(storeRefs, api)
  }
}


const filterTable = () => {
  if(hott()){
    const fp = hott().getPlugin('filters')
    fp.removeConditions(2)
    fp.addCondition(2,'contains', [currentSearch.value])
    fp.filter()
  }
}
// register Handsontable's modules
registerAllModules();

watch([columns.value.dirty, tags.value.dirty, activeTable, dirty], () => {
  log.debug(`${dirty.value} rendering inventory`, activeTable.value)
  let u = updateTable()
  saveStore()
})

</script>

<script lang="ts">
import { defineComponent, computed, PropType, defineProps, defineEmits, watch} from 'vue';
import { registerAllModules } from 'handsontable/registry';
import { DefaultSettings, InventoryTable, InventoryTableOptions, TableRecipe } from '../lib/table';
import { Columns, ColumnByNames, ColumnInfo } from '../lib/columns';
import { TricksterItem} from '../lib/trickster';
import Handsontable from 'handsontable';
import { useStoreRef, saveStore } from '../state/state';
import { storage } from '../session_storage';
import { getLTOState, LTOApi, LTOApiv0 } from '../lib/lifeto';
import log, { info } from 'loglevel';
import { OrderDetails, OrderSender } from '../lib/lifeto/order_manager';
</script>

<style src="handsontable/dist/handsontable.full.css">
</style>
