import axios from 'axios'

export default {
    namespaced: true,
    state: {
        propertyTypes: [],
        propertyType: {
            description: '',
            usageType: 0,
        },
    },
    mutations: {
        setPropertyTypes(state, types) {
            state.propertyTypes = types
        },
        setPropertyType(state, type) {
            state.propertyType = type
        },
        addToPropertyTypes(state, type) {
            state.propertyTypes.push(type)
        },
        updatePropertyTypes(state, type) {
            state.propertyTypes.find((item) => item.id === type.id).description =
                type.description
            state.propertyTypes.find((item) => item.id === type.id).usageType =
                type.usageType
        },
        clearPropertyType(state) {
            state.propertyType = {
                description: '',
                usageType: 0,
            }
        },
        removePropertyType(state, id) {
            state.propertyTypes.pop(state.propertyTypes.find((p) => p.id === id))
        },
    },
    getters: {},
    actions: {
        getPropertyTypes({ commit }) {
            axios
                .get('/api/PropertyType')
                .then((result) => commit('setPropertyTypes', result.data))
                .catch(console.error)
        },
        getPropertyType({ commit }, id) {
            axios
                .get(`/api/PropertyType/${id}`)
                .then((result) => commit('setPropertyType', result.data))
                .catch(console.error)
        },
        savePropertyType({ commit }, item) {
            axios
                .post('/api/PropertyType', item)
                .then((result) => {
                    console.log('save')
                    commit('addToPropertyTypes', result.data)
                })
                .catch(console.error)
        },
        updatePropertyType({ commit }, item) {
            axios
                .put('/api/PropertyType', item)
                .then((result) => commit('updatePropertyTypes', item))
                .catch(console.error)
        },
        clearPropertyType({ commit }) {
            commit('clearPropertyType')
        },
        deletePropertyType({ commit }, id) {
            axios
                .delete(`/api/PropertyType/${id}`)
                .then((result) => commit('removePropertyType', id))
                .catch(console.error)
        },
    },
}