import axios from 'axios'

export default {
    namespaced: true,
    state: {
        contactUsSources: [],
        contactUsSource: {
            description: '',
        },
    },
    mutations: {
        setContactUsSources(state, sources) {
            state.contactUsSources = sources
        },
        setContactUsSource(state, source) {
            state.contactUsSource = source
        },
        addToContactUsSources(state, source) {
            state.contactUsSources.push(source)
        },
        updateContactUsSources(state, source) {
            state.contactUsSources.find((item) => item.id === source.id).description =
                source.description
        },
        clearContactUsSource(state) {
            state.contactUsSource = {
                description: '',
            }
        },
        removeContactUsSource(state, id) {
            state.contactUsSources.pop(
                state.contactUsSources.find((p) => p.id === id),
            )
        },
    },
    getters: {},
    actions: {
        getContactUsSources({ commit }) {
            axios
                .get('/api/MailSource')
                .then((result) => {
                    commit('setContactUsSources', result.data)
                })
                .catch(console.error)
        },
        getContactUsSource({ commit }, id) {
            axios
                .get(`/api/MailSource/${id}`)
                .then((result) => {
                    commit('setContactUsSource', result.data)
                })
                .catch(console.error)
        },
        saveContactUsSource({ commit }, item) {
            axios
                .post('/api/MailSource', item)
                .then((result) => {
                    commit('addToContactUsSources', result.data)
                })
                .catch(console.error)
        },
        updateContactUsSource({ commit }, item) {
            axios
                .put('/api/MailSource', item)
                .then((result) => {
                    console.log('updateContactUsSources')
                    console.log(item)
                    commit('updateContactUsSources', item)
                })
                .catch(console.error)
        },
        clearContactUsSource({ commit }) {
            commit('clearContactUsSource')
        },
        deleteContactUsSource({ commit }, id) {
            axios
                .delete(`/api/MailSource/${id}`)
                .then((result) => commit('removeContactUsSource', id))
                .catch(console.error)
        },
    },
}