import { defineStore } from 'pinia'

import {
  IAccount,
  ICircuit, ICircuitState, IGlobalState, IGroupShort, IMyCircuit, IMyGroup,
} from '@src/model'
import { tools } from '@store/Modules/tools'
import translate from '@src/globalroutines/util'

import * as Types from '@src/store/Api/ApiTypes'
import { useGlobalStore } from '@store/globalStore'
import { serv_constants } from '@store/Modules/serv_constants'
import { Api } from '@api'
import { toolsext } from '@store/Modules/toolsext'
import { static_data } from '@src/db/static_data'
import { useUserStore } from '@store/UserStore'


import { shared_consts } from '@/common/shared_vuejs'
import { costanti } from '@costanti'

import globalroutines from '../globalroutines/index'

export const useCircuitStore = defineStore('CircuitStore', {
  state: (): ICircuitState => ({
    listcircuits: [],
    listaccounts: [],
  }),

  getters: {},

  actions: {
    getRemainingCoinsToSend(account: IAccount) {
      if (account)
        return tools.roundDec2(account.saldo + account.fidoConcesso)
      else
        return 0
    },
    getMaxCoinsToSend(account: IAccount) {
      if (account)
        return tools.roundDec2(account.qta_maxConcessa - account.saldo)
      else
        return 0
    },
    getSaldoByCircuitId(circuitId: string): number {
      const userStore = useUserStore()
      const account = userStore.my.profile.useraccounts.find((rec: IAccount) => rec.circuitId === circuitId)
      if (account)
        return account.saldo
      else
        return 0
    },

    getCircuitClass(circuit: ICircuit) {
      if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE3_MONETA_ABILITATA)
        return 'circuito_abilitato'
      else if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE2_ORGANIZZAZIONE)
        return 'circuito_fase_2'
      else if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE1_CREAZIONE_GRUPPO)
        return 'circuito_in_creazione'
    },

    getColorCircuitClass(circuit: ICircuit) {
      if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE3_MONETA_ABILITATA)
        return 'green'
      else if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE2_ORGANIZZAZIONE)
        return 'orange'
      else if (circuit.status === shared_consts.CIRCUIT_STATUS.FASE1_CREAZIONE_GRUPPO)
        return 'red'
    },

    getCircuitByName(circuitname: string): ICircuit | undefined | null  {
      return this.listcircuits.find((rec: ICircuit) => rec.name === circuitname)
    },

    getCircuitByProvince(prov: string): ICircuit | undefined | null  {
      return this.listcircuits.find((rec: ICircuit) => rec.strProv === prov)
    },

    getCircuitByCircuitId(circuitId: string): ICircuit | null | undefined {
      return this.listcircuits.find((rec: ICircuit) => rec._id === circuitId)
    },

    getNameByCircuitId(circuitId: string): string  {
      const circuit = this.getCircuitByCircuitId(circuitId);
      return circuit && circuit.name ? circuit.name : ''
    },

    getCircuitsLabelValue(): any  {
      let arr = []
      for (const circ of this.listcircuits) {
        arr.push({label: circ.name, value: circ._id})
      }
      return arr
    },

    getCircuitByPath(circuitpath: string): ICircuit | null  {
      const ris = this.listcircuits.find((rec: ICircuit) => rec.path === circuitpath)
      return ris ? ris : null
    },

    async loadCircuits() {
      return Api.SendReq('/users/circuits', 'POST', null)
        .then((res) => {
          return res.data
        }).catch((error) => {
          return {}
        })

    },

    getCircuitsListByGroup(mygrp: IMyGroup): ICircuit[]  {
      return this.listcircuits.filter((rec: ICircuit) => mygrp.mycircuits!.findIndex((circ: IMyCircuit) => circ.circuitname === rec.name) >= 0)
    },

    IsAskedCircuitByNameAndGroup(name: string, groupname: string): boolean {
      let circuit = this.listcircuits.find((circ: ICircuit) => circ.name === name)
      if (circuit && circuit.req_groups) {
        return circuit.req_groups?.findIndex((grp: IGroupShort) => grp.groupname === groupname) >= 0
      }
      return false
    },

    getAccountByCircuitId(circuitId: string): any {
      if (this.listaccounts) {
        return this.listaccounts.find((rec: IAccount) => rec.circuitId === circuitId)
      }
      return null
    },
    getAccountsListNameValue(): any[] {
      let arr = []

      if (this.listaccounts) {
        for (const acc of this.listaccounts) {
          let chi = acc.username ? acc.username : (acc.groupname ? 'Collettivo: ' + acc.groupname : 'Comunitario: ' + acc.contocom)
          if (acc.circuitId) {
            chi = '[' + this.getNameByCircuitId(acc.circuitId) + '] ' + chi
          }
          arr.push({label: chi, value: acc._id})
        }
      }
      return arr
    },

    getSortFieldsAvailable(): any[] {
      return [{ label: 'Nome', value: 'name' }, { label: 'Iscritti', value: 'numMembers' }]
    },

  },
})
