const encryptionStore = {
    namespaced: true,
    state: () => (
        {
            aes_key: null,
            keyPair: null,
        }
    ),

    mutations: {
        lock (state) {
            state.aes_key = null
            state.keyPair = null
        },

        updateAesKey (state, key) {
            state.aes_key = key
        },

        updateKeyPair (state, keyPair) {
            state.keyPair = keyPair
        },
    },
}

const storeMixin = {
    state: () => (
        {
            items: [],
            headers: [],
        }
    ),

    mutations: {
        lock (state) {
            state.items = []
        },

        addItem (state, item) {
            state.items.push(item)
        },

        removeItem (state, id) {
            state.items = state.items.filter(i => i.id != id)

            Swal.fire({title: "{{_('Successfully deleted!') | escapejs}}", icon: "success", position:"top-end", showConfirmButton: false, toast: true, timer: 1000})
        },

        editItem (state, item_edited) {
            state.items = state.items.map(i => {
                if (i.id == item_edited.id) {
                    return item_edited
                }

                return i
            })

            Swal.fire({title: "{{_('Successfully edited') | escapejs}}", icon: "success", position:"top-end", showConfirmButton: false, toast: true, timer: 1000})
        },
    },

    getters: {
        encryptedFields (state) {
            return state.headers.filter(e => e.encrypted).map(e => e.value)
        },

        getById: (state) => (id) => {
            return state.items.find(e => e.id == id)
        },
    },

    actions: {
        async setItems ({ commit, getters }, payload) {
            return payload.items.map(async item => {
                const new_item = await payload.self.decryptObject(getters.encryptedFields, item)

                return await commit('addItem', new_item)
            })
        },

        async addItem ({ getters, commit }, payload) {

            const new_item = await payload.self.decryptObject(getters.encryptedFields, payload.item)

            return await commit('addItem', new_item)

        },
    }
}

const itemStore = {__proto__: storeMixin, namespaced: true}
const typeStore = {__proto__: storeMixin, namespaced: true}
const relationStore = {__proto__: storeMixin, namespaced: true}
const propertyStore = {__proto__: storeMixin, namespaced: true}
const linkedPropertyStore = {__proto__: storeMixin, namespaced: true}
const relationPropertyStore = {__proto__: storeMixin, namespaced: true}
const history = {__proto__: storeMixin, namespaced: true}

const store = new Vuex.Store({
    modules: {
        encryption: encryptionStore,
        items: itemStore,
        types: typeStore,
        relations: relationStore,
        properties: propertyStore,
        linkedProperties: linkedPropertyStore,
        relationProperties: relationPropertyStore,
        history: history,
    }
})
