import { defineStore } from 'pinia'
import { Api } from '@api'

import { serv_constants } from './Modules/serv_constants'

import { INotif, INotifState } from '../model'
import { tools } from '@src/store/Modules/tools'
import { NotifDefault } from '@src/model'
import { shared_consts } from '@src/common/shared_vuejs'
import { useUserStore } from '@store/UserStore'

export const useNotifStore = defineStore('NotifStore', {
  state: (): INotifState => ({
    last_notifs: [],
    show_all: true,
    updateNotification: false,
    countNotif: 0,
  }),

  getters: {

    getlasts_notifs: (mystate: INotifState) => (): INotif[] => {
      const ctrec = (mystate.last_notifs) ? mystate.last_notifs.slice(0, 20).filter((rec) => (mystate.show_all ? true : !rec.read) && (rec.typedir !== shared_consts.TypeNotifs.TYPEDIR_CIRCUITS)) : []
      return (ctrec)

    },

    getlasts_coins: (mystate: INotifState) => (): INotif[] => {
      const ctrec = (mystate.last_notifs) ? mystate.last_notifs.slice(0, 20).filter((rec) => (mystate.show_all ? true : !rec.read) && (rec.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS)) : []
      return (ctrec)

    },

    getnotifs_coinsreq: (mystate: INotifState) => (): INotif[] => {
      const ctrec = (mystate.last_notifs) ? mystate.last_notifs.slice(0, 20).filter((rec) => rec.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS && rec.typeid === shared_consts.TypeNotifs.ID_CIRCUIT_SENDCOINSREQ && rec.status === 0) : []
      return (ctrec)

    },

    getnumNotifUnread: (mystate: INotifState) => () => {
      const myarr = mystate.last_notifs.filter((notif) => !notif.read && (notif.typedir !== shared_consts.TypeNotifs.TYPEDIR_CIRCUITS))
      return (tools.isArray(myarr) ? myarr.length : 0)
    },

    getnumCoinsUnread: (mystate: INotifState) => () => {
      const myarr = mystate.last_notifs.filter((notif) => !notif.read && (notif.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS))
      return (tools.isArray(myarr) ? myarr.length : 0)
    },

  },
  actions: {

    updateArrNotif() {
      this.setBadgeIconApp()
    },

    setNotif(notif: INotif) {
      console.log('setNotif', notif)
      if (notif) {
        this.last_notifs = [notif, ...this.last_notifs]
      }
      this.updateArrNotif()

    },

    setAsRead(idnotif: string) {
      const rec = this.last_notifs.find((rec: any) => rec._id === idnotif)
      if (rec) {
        rec.read = true
      }

      this.updateArrNotif()
    },

    updateRecNotif(recnotif: INotif) {
      if (recnotif) {
        const myrec = this.last_notifs.find((rec: any) => rec._id === recnotif._id)
        if (myrec) {
          myrec.status = recnotif.status
          myrec.read = recnotif.read
          myrec.descr = recnotif.descr

          this.updateArrNotif()
        }
      }
    },

    async setBadgeIconApp(){
      // Get our dummy count and update it,
      // just to give more context for this demo.
      const countNow = this.getnumNotifUnread()

      try {
        // @ts-ignore
        await navigator.setAppBadge(countNow)
          .catch((error: any) => { /* ... */
          });
      }catch (e) {

      }
    },

    setAllRead(username: string, qualinotif: number) {
      return Api.SendReq(`/sendnotif/setall/${username}/${qualinotif}/${process.env.APP_ID}`, 'GET', null)
        .then((res) => {
          // console.log('res', res)
          if (res) {
            for (const rec of this.last_notifs) {
              rec.read = true
            }
          }
          this.updateArrNotif()

        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    setRead(_id: string) {
      return Api.SendReq(`/sendnotif/set/${_id}/${process.env.APP_ID}`, 'GET', null)
        .then((res) => {
          // console.log('res', res)
          if (res) {
            const rec = this.last_notifs.find((rec: any) => rec._id === _id)
            if (rec) {
              rec.read = true
            }
          }
          this.updateArrNotif()

        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    deleteRec(username: string, id: string) {
      return Api.SendReq(`/sendnotif/del/${username}/${id}/${process.env.APP_ID}`, 'GET', null)
        .then((res) => {
          // console.log('res', res)
          if (res) {
            this.last_notifs = this.last_notifs.filter((rec) => rec._id !== id)
          }

          this.updateArrNotif()
        })
        .catch((error) => {
          console.error(error)
          return false
        })

    },

    deleteAll(username: string, qualinotif: number) {
      return Api.SendReq(`/sendnotif/delall/${username}/${qualinotif}/${process.env.APP_ID}`, 'GET', null)
        .then((res) => {
          // console.log('res', res)
          if (res) {
            if (qualinotif === shared_consts.QualiNotifs.CIRCUITS)
              this.last_notifs = this.last_notifs.filter((rec: INotif) => rec.typedir !== shared_consts.TypeNotifs.TYPEDIR_CIRCUITS)
            else if (qualinotif === shared_consts.QualiNotifs.OTHERS)
              this.last_notifs = this.last_notifs.filter((rec: INotif) => rec.typedir === shared_consts.TypeNotifs.TYPEDIR_CIRCUITS)
            this.updateArrNotif()
          }

        })
        .catch((error) => {
          console.error(error)
          return false
        })

    },

    deactivateRec(id: string) {
      return ''
    },

    async updateNotifDataFromServer({ username, lastdataread }: {username: string, lastdataread: Date}) {
      console.log('updateNotifDataFromServer', username, lastdataread)

      return Api.SendReq(`/sendnotif/${username}/${lastdataread}/${process.env.APP_ID}`, 'GET', null)
        .then((res) => {
          // console.log('res', res)
          if (!!res.data && !!res.data.arrnotif) {
            this.last_notifs = res.data.arrnotif
          } else {
            this.last_notifs = []
          }
          this.updateArrNotif()
          tools.updateMyData(res.data)
          return true
        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    async SendNotifEvent(notif: INotif) {
      console.log('SendNotifEvent', notif)

      const userStore = useUserStore()


      const data: INotif = { ...NotifDefault, ...notif }

      data.idapp = process.env.APP_ID
      data.typedir = notif.typedir
      data.typeid = notif.typeid
      data.sender = notif.sender
      data.dest = notif.dest
      data.title = notif.title
      data.descr = notif.descr
      data.datenotif = tools.getDateNow()
      data.read = false

      // console.log('DOPO:')
      // console.table(data)

      return Api.SendReq('/sendnotif', 'POST', data)
        .then((res) => {
          console.log('res', res)
          if (res.status === 200) {
            if (res.data.code === serv_constants.RIS_CODE_OK && res.data.record) {
              if (res.data.record.dest === userStore.my.username) {
                this.setNotif(res.data.record)
              }
              return true
            }
          }
          return false
        })
        .catch((error) => {
          console.error(error)
          return false
        })
    },

    setCountNotifs(num: number) {
      this.countNotif = num
    },
  },

})
