import {
    deleteCountdownTimerById,
    getCountdownTimerFolderId,
    listCountdownTimerImages,
    listCountdownTimers,
    moveCountdownTimerFileToFolder,
    saveCountdownTimerItem,
    uploadCountdownTimerImage,
} from "@/module/conutdown-timer/service/countdown-timer-service";

export default {
    namespaced: true,
    state: {
        countdown_timer_list: [],
        edit_countdown_timer_data: JSON.parse(sessionStorage.getItem('edit_countdown_timer_data')) || {},
        images: [],
    },
    actions: {
        async getCountdownTimerList({rootState, commit, dispatch}, corporate_customer_id) {
            const client = rootState.directus.client
            const result = await listCountdownTimers(client, corporate_customer_id);
            commit("countdown_timer_list", result)
        },
        async deleteCountdownTimer({rootState, commit, dispatch}, id) {
            const client = rootState.directus.client
            await deleteCountdownTimerById(client, id);
            await dispatch("getCountdownTimerList", rootState.user.current_corporate_customer)
        },
        async saveCountdownTimer({rootState, commit, dispatch}, options) {
            const client = rootState.directus.client
            return await saveCountdownTimerItem(client, options)
        },
        async getImages({rootState, commit, dispatch}) {
            const client = rootState.directus.client
            const result = await listCountdownTimerImages(client)
            commit("images", result)
        },
        async getFolder({rootState, commit, dispatch}) {
            const client = rootState.directus.client
            return await getCountdownTimerFolderId(client)
        },
        async changeFileFolder({rootState, commit, dispatch}, fileId) {
            const client = rootState.directus.client
            const folderId = await dispatch('getFolder')
            await moveCountdownTimerFileToFolder(client, fileId, folderId)
        },
        async uploadImages({rootState, commit, dispatch}, file) {
            const client = rootState.directus.client
            const folderId = await dispatch('getFolder')
            const result = await uploadCountdownTimerImage(client, file, folderId)
            commit("addNewImage", {url: result.url})
        }
    },
    mutations: {
        countdown_timer_list(state, val) {
            state.countdown_timer_list = val
        },
        edit_countdown_timer_data(state, val) {
            state.edit_countdown_timer_data = val
        },
        images(state, val) {
            state.images = val
        },
        addNewImage(state, val) {
            state.images.unshift(val)
        }
    },
    getters: {}
}
