import { Buffer } from 'buffer'
import _ from '@/plugins/lodash'
import dayjs from '@/plugins/dayjs'

const getDefaultState = () => {
  const state = {
    notShowMessagesAgain: {
      byId: {
        default: []
      }
    }
  }
  return state
}
const state = getDefaultState()

const mutations = {
  SET_NOT_SHOWMESSAGES_AGAIN (state, payload) {
    const { id, value } = payload
    const notShowMessagesAgain = state.notShowMessagesAgain
    notShowMessagesAgain.byId = {
      ...state.notShowMessagesAgain.byId,
      [id]: value
    }
    state.notShowMessagesAgain = _.cloneDeep(notShowMessagesAgain)
  }
}

const actions = {
  addNotShowMessagesAgain ({ commit, state, rootState }, payload) {
    const userId = rootState.auth.userId || 'default'
    const messages = state.notShowMessagesAgain.byId[userId] || []
    messages.unshift({
      key: payload,
      at: new Date()
    })
    commit('SET_NOT_SHOWMESSAGES_AGAIN', {
      id: Buffer.from(userId).toString('base64'),
      value: _.uniqBy(messages, 'key')
    })
  }
}

const getters = {
  showMessageAgain: (state, getter, rootState) => (key) => {
    const userId = Buffer.from(rootState.auth.userId).toString('base64') || 'default'
    const messages = state.notShowMessagesAgain.byId[userId] || []
    const message = messages.find((item) => item.key === key)
    return !message || !dayjs(message.at).isToday()
  }
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}
