import { toRaw } from 'vue'
import { loggerInfo } from './StaticData'
import { Logger } from '3-class-complex-assistants'

const initState = {
  isPushToServer: true,

  serviceInfo: loggerInfo,
  loggerData: null,
  loggerAnswer: null
};

const state = {
  ...initState
};

const getters = {
  loggerData: (state) => state.loggerData,
  loggerAnswer: (state) => state.loggerAnswer,
};

const mutations = {
  setIsPushToServer: (state, updval) =>  state.isPushToServer = updval,
  setServiceInfo: (state, updval) =>  state.serviceInfo = updval,
  setLoggerData: (state, updval) =>  state.loggerData = updval,
  setLoggerAnswer: (state, updval) =>  state.loggerAnswer = updval,
  resetStore: (state) => {
    Object.entries(initState).forEach(([k,v]) => {
      state[k] = v
    })
  },
};

const actions = {
  uploadData: async ({commit, state}, data) => {
    try{

      const callFunc = (text) => (`answerMessage: ${text}`)

      const isPushToServer = toRaw(state.isPushToServer)
      const serviceInfo = toRaw(state.serviceInfo)
      const status = data.status
      const text = data.text
      const allParams = {...serviceInfo, callFunc, isPushToServer}
      const logger = new Logger(allParams)
      
      const loggerAnswer = (status) => {
        const curStatus = status.toLowerCase()
        switch (curStatus) {
        case 'debug': return logger.debug(text, -1)
        case 'info': return logger.info(text, 0)
        case 'warn': return logger.warn(text, 1)
        case 'error': return logger.error(text, 2)
        default: return callFunc('Неизвестный статус логгера')
        }
      }

      commit('setLoggerData', data)
      commit('setLoggerAnswer', loggerAnswer(status))

    } catch (err) {
      console.error(err)
    }
  },

  resetStore: ({commit}) => {
    commit('resetStore')
  }
};

export const store = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
