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 useNodeStore = defineStore('node', {
    state: () => ({
        nodes: [],
        loading: false,
        empty: true,
        error: null,
        pagination: {},
        query: {},
    }),
    getters: {
        getById: (state) => {
            return (id) => state.nodes.find(p => p.id === id)
        }
    },
    actions: {
        async setSearch(query) {
            this.query = query;
            this.query.type = 'search';
            await this.loadNodes();
        },
        async setQuery(query) {
            this.query = query;
            this.query.type = 'list';
            await this.loadNodes();
        },
        async locate(address) {
            const params = new URLSearchParams();
            let error = null;
            params.append('address', address);
            const data = await performRequest(this, "GET", `${config.backendUrl}/nodes/locate/${params.size === 0 ? '' : '?'}${params.toString()}`, null, true, 'Geocoding error').catch(e => {
                error = e.errorObj;
            });
            return {node: data?.data, error: error};
        },
        async addNode(name, address, location, country ) {

            const body = {
                name: name,
                address: address,
                location: location,
                country: country
            }

            const data = await performRequest(this, "PUT", `${config.backendUrl}/nodes/`, body, true);
            return data.data;
        },
        async loadNodes() {

            const params = new URLSearchParams();

            if (this.query.searchTerm)
                params.append('filter', this.query.searchTerm);

            if (this.query.nodeType)
                params.append('node_type', this.query.nodeType);

            if (this.query.includeUserNode)
                params.append('include_user_node', this.query.includeUserNode);

            if (this.query?.page)
                params.append('page', this.query.page);

            if (this.query?.pageSize)
                params.append('limit', this.query.pageSize);


            const endpoint = this.query.type === 'list' ? '/nodes' : '/nodes/search'
            const url = `${config.backendUrl}${endpoint}/${params.size === 0 ? '' : '?'}${params.toString()}`;


            const {data: data, headers: headers} = await performRequest(this, "GET", url, null, true);


            if (this.query.type === 'list')
                this.pagination = {
                    page: parseInt(headers.get('X-Current-Page')),
                    pageCount: parseInt(headers.get('X-Page-Count')),
                    totalCount: parseInt(headers.get('X-Total-Count'))
                };


            this.loading = false;
            this.empty = data.length === 0;
            this.nodes = data;

        }
    }
});
