import { defineStore } from 'pinia'

import type {
  IAccount,
  ICircuit, ICircuitState, IGroupShort, IMyCircuit, IMyGroup, IUserFields
} from '@src/model';
import {
  IGlobalState
} from '@src/model'
import { tools } from '@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 { useNotifStore } from '@store/NotifStore'


import { shared_consts } from '@src/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
    },

    sonoDentroAlCircuitoNazionale() {
      const userStore = useUserStore()

      const circNazionali: any = this.listcircuits.filter((circ: any) => circ.showAlways)

      for (const circ of circNazionali) {
        const trovato = userStore.my.profile.mycircuits.findIndex((mycirc: any) => mycirc.circuitname === circ.name) >= 0
        if (trovato) {
          return true
        }
      }

      return false

    },

    getCircuitoNazionale(arrCircuiti: any): any {

      const circNazionali: any = this.listcircuits.filter((circ: any) => circ.showAlways)

      for (const circ of circNazionali) {
        const reccirc = arrCircuiti.find((mycirc: any) => mycirc.circuitname === circ.name)
        if (reccirc) {
          return reccirc
        }
      }

      return null

    },

    EDentroAlCircuitoNazionale(user: IUserFields) {

      const circNazionali: any = this.listcircuits.filter((circ: any) => circ.showAlways)

      if (user && user.profile && user.profile.mycircuits && user.profile.mycircuits.length > 0) {
        for (const circ of circNazionali) {
          const trovato = user.profile.mycircuits.findIndex((mycirc: any) => mycirc.circuitname === circ.name) >= 0
          if (trovato) {
            return true
          }
        }
      }

      return false

    },

    isCircuitNational(circuitname: string): boolean {
      return this.listcircuits.findIndex((rec: ICircuit) => rec.name === circuitname && rec.showAlways) >= 0
    },

    getCircuitsNational(): any[] {
      const userStore = useUserStore()
      let arrcircnaz = this.listcircuits.filter((rec: ICircuit) => rec.showAlways)

      for (const circ of arrcircnaz) {
        if (userStore.my.profile.useraccounts)
          circ.account = userStore.my.profile.useraccounts.find((rec: IAccount) => rec.circuitId === circ._id)
      }

      return arrcircnaz
    },

    IsNationalAndNotEnterInLocal(circuitname: string): boolean {
      const userStore = useUserStore()

      return this.isCircuitNational(circuitname) && userStore.my.profile.mycircuits.length <= 0

    },

    SonoDentroAdAlmeno1CircuitoConFido(): boolean {
      const userStore = useUserStore()

      if (userStore.my.profile.useraccounts) {
        const accountsConFido = userStore.my.profile.useraccounts.filter((rec: IAccount) => rec.fidoConcesso > 0)

        for (const account of accountsConFido) {
          const mycircuit = this.listcircuits.find((circ: ICircuit) => circ._id === account.circuitId)
          if (mycircuit && !mycircuit.showAlways) {
            return true
          }
        }
      }

      return false
    },

    get1CircuitoConFido() {
      const userStore = useUserStore()

      if (userStore.my.profile.useraccounts) {
        const accountsConFido = userStore.my.profile.useraccounts.filter((rec: IAccount) => rec.fidoConcesso > 0)

        for (const account of accountsConFido) {
          const mycircuit = this.listcircuits.find((circ: ICircuit) => circ._id === account.circuitId)
          if (mycircuit && !mycircuit.showAlways) {
            return mycircuit
          }
        }
      }

      return null
    },

    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)
    },

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

    getCircuitsByProvince(prov: string): ICircuit[] {
      return this.listcircuits.filter((rec: ICircuit) => rec.strProv === prov)
    },

    getCircuitsNameByProvince(prov: string): ICircuit[] {
      const filterarr = this.listcircuits.filter((rec: ICircuit) => rec.strProv === prov)
      let arrcirc = filterarr.map((subArray: any) => {
        return subArray.name;
      })
      if (arrcirc.length > 1)
        return ['[Nessuno]', ...arrcirc]
      else
        return arrcirc
    },

    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 {}
        })

    },

    async aggiornaSaldo(circuitId: string, groupname: string) {
      const userStore = useUserStore()
      const notifStore = useNotifStore()

      const username = userStore.my.username
      const lastdr = notifStore.getLastDataRead(username)

      return Api.SendReq('/users/updatesaldo', 'POST', { circuitId, groupname, lastdr })
        .then((res) => {
          if (res.data.ris)
            tools.updateMyData(res.data.ris)
        }).catch((error) => {
          return {}
        })

    },

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

      return []
    },

    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 ? 'Gruppo: ' + 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' }]
    },

  },
})
