import { computed, defineComponent, onMounted, PropType, ref, watch } from 'vue'

import { IAccount, ICircuit, IOperators, ISendCoin, ISpecialField, IUserFields } from '../../model'
import { tools } from '@store/Modules/tools'
import { CSaldo } from '@/components/CSaldo'
import { useUserStore } from '@store/UserStore'
import { useCircuitStore } from '@store/CircuitStore'
import { useQuasar } from 'quasar'
import { useI18n } from '@/boot/i18n'
import { CMyUserOnlyView } from '@/components/CMyUserOnlyView'
import { costanti } from '@costanti'

export default defineComponent({
  name: 'CSendCoins',
  emits: ['close'],
  props: {
    showprop: {
      type: Boolean,
      default: false,
    },
    circuitname: {
      type: String,
      default: ''
    },
    to_user: {
      type: Object as PropType<IUserFields>,
      required: true,
    },
  },
  components: { CSaldo, CMyUserOnlyView },

  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const show = ref(false)
    const userStore = useUserStore()
    const circuitStore = useCircuitStore()


    const from_username = ref(userStore.my.username)
    const circuitsel = ref('')
    const qty = ref(<string|number>'')
    const causal = ref('')
    const bothcircuits = ref(<any>[])

    const circuitloaded = ref(<ICircuit | undefined>undefined)
    const circuitdest = ref(<ICircuit | undefined>undefined)
    const accountloaded = ref(<IAccount | undefined>undefined)
    const accountdest = ref(<IAccount | undefined>undefined)
    const remainingCoins = ref(0)
    const maxsendable = ref(0)
    const numstep = ref(0)

    const priceLabel = computed(() => circuitloaded.value ? `${qty.value} ` + circuitloaded.value.symbol : '')
    const arrayMarkerLabel = ref(<any>[])

    const qtyRef = ref(<any>null)
    const causalRef = ref(<any>null)

    watch(() => circuitsel.value, (newval, oldval) => {
      tools.setCookie(tools.CIRCUIT_USE, newval)
      aggiorna()
    })

    watch(() => props.showprop, (newval, oldval) => {
      console.log('props.showprop', props.showprop, newval)
      show.value = newval
    })

    function aggiorna() {
      circuitloaded.value = circuitStore.listcircuits.find((rec: ICircuit) => rec.name === circuitsel.value)
      if (circuitloaded.value) {
        accountloaded.value = userStore.getAccountByCircuitId(circuitloaded.value._id)
        // accountdest.value = userStore.getAccountByCircuitId(circuitloaded.value._id)
        if (accountloaded.value) {
          remainingCoins.value = circuitStore.getRemainingCoinsToSend(accountloaded.value)
          if (accountloaded.value.saldo > 0) {
            maxsendable.value = accountloaded.value.saldo + accountloaded.value.fidoConcesso
          } else {
            maxsendable.value = accountloaded.value.fidoConcesso
          }

          if (remainingCoins.value < 10) {
            remainingCoins.value = 10
          }

          numstep.value = Math.round(maxsendable.value / 10)
          if (numstep.value < 1) {
            numstep.value = 1
          }

          const quanti = [...Array(20).keys()].map(i => i + 1)
          for (const ind of quanti) {
            let valuenorm = ind * numstep.value
            let value = ind * numstep.value
            if (value > remainingCoins.value) {
              break
            } else {
              const label = valuenorm.toString()
              arrayMarkerLabel.value.push({ value, label })
            }
          }
        }

      }
    }

    function mounted() {


      // ....
      if (props.to_user) {
        console.log('user', props.to_user)
        bothcircuits.value = userStore.IsMyCircuitByUser(props.to_user)

        if (props.circuitname) {
          circuitsel.value = props.circuitname
        } else {
          circuitsel.value = tools.getCookie(tools.CIRCUIT_USE, bothcircuits.value[0])
        }
        if (!userStore.IsMyCircuitByName(circuitsel.value)) {
          circuitsel.value = bothcircuits.value[0]
        }

        aggiorna()

        show.value = true
      }
    }

    function hide() {
      emit('close', true)
    }

    function sendCoin() {
      console.log('sendcoin', qty.value, props.to_user.username)

      if (props.to_user.username && qty.value && circuitloaded.value) {
        const myrecsendcoin: ISendCoin = {
          qty: tools.convstrToNum(qty.value),
          dest: props.to_user.username,
          circuitname: circuitsel.value,
          causal: causal.value,
          symbol: circuitloaded.value.symbol,
        }
        if (myrecsendcoin) {
          tools.sendCoinsByCircuit($q, circuitloaded.value, myrecsendcoin)
            .then((ris: any) => {
              if (ris) {
                show.value = false
              }
            })
        }
      }
    }

    onMounted(mounted)

    return {
      t,
      tools,
      show,
      bothcircuits,
      from_username,
      circuitsel,
      circuitloaded,
      accountloaded,
      accountdest,
      qty,
      hide,
      sendCoin,
      causal,
      priceLabel,
      arrayMarkerLabel,
      remainingCoins,
      qtyRef,
      causalRef,
      maxsendable,
      circuitStore,
      numstep,
      costanti,
      userStore,
    }
  },
})
