import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import performRequest from "@/backend.js";
import logger from "@/logger.js";


export const useAppsStore = defineStore('apps', {
    state: () => ({
        apps: [],
        loading: false,

    }),
    getters: {
        getById: (state) => {
            return (id) => state.apps.find(p => p.id === id)
        }
    },
    actions: {
        async loadApps() {
            this.loading = true;
            const url = `${config.backendUrl}/apps`;
            const resp = await performRequest(this, 'GET', url, null);
            this.apps = resp.data;
            this.loading = false;
        },
        async addApp(appName, appGroups) {
            const url = `${config.backendUrl}/apps`;

            const app = {
                name: appName,
                groups: [],
            }

            for (const [key, value] of Object.entries(appGroups)) {
                if (value) {
                    app.groups.push(key);
                }
            }


            const resp = await performRequest(this, 'POST', url, app);
            this.apps.push(resp.data);
            return resp.data;
        },
        async updateApp(appId, appName, appGroups) {
            const url = `${config.backendUrl}/apps/${appId}`;

            const app = {
                id: appId,
                name: appName,
                groups: [],
            };

            for (const [key, value] of Object.entries(appGroups)) {
                if (value) {
                    app.groups.push(key);
                }
            }

            const resp = await performRequest(this, 'POST', url, app);
            const index = this.apps.findIndex(a => a.id === app.id);
            this.apps[index] = resp.data;
        },
        async deleteApp(appId) {
            const url = `${config.backendUrl}/apps/${appId}`;
            await performRequest(this, 'DELETE', url, null, false);
            this.apps = this.apps.filter(a => a.id !== appId);
        }

    }
});