import toast from 'react-hot-toast';
import axiosInstance from '../../util/axiosInstance';
import {
    addSplitter,
    removeSplitter,
    updateSplitter,
} from '../reducers/currentClusterReducer';

export const addSplitterToCluster =
    (splitterInfo, callback) => async (dispatch, getState) => {
        const {
            currentClusterReducer: { currentCluster },
        } = getState();

        try {
            const { data } = await axiosInstance.post('/splitters', {
                ...splitterInfo,
                cluster_id: currentCluster.id,
            });
            dispatch(addSplitter(data));
            callback(data);
            toast.success('Successfully Added Splitter');
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const updateSplitterDetail =
    (splitterId, splitterInfo, callback) => async (dispatch) => {
        try {
            const { data } = await axiosInstance.put(
                `/splitters/${splitterId}`,
                splitterInfo
            );
            dispatch(updateSplitter(data));
            callback(data);
            toast.success('Successfully Updated Splitter');
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const deleteSplitterFromCluster =
    (splitterId, callback) => async (dispatch) => {
        try {
            await axiosInstance.delete(`/splitters/${splitterId}`);
            dispatch(removeSplitter(splitterId));
            toast.success('Successfully Deleted Splitter');
            callback();
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const disconnectSplitterParent = (splitterId, callback) => async () => {
    try {
        await axiosInstance.delete(
            `/splitters/${splitterId}/disconnect-parent`
        );
        callback();
        toast.success('Parent disconnected successfully');
    } catch (error) {
        toast.error(error.response.data.message);
    }
};

export const disconnectSplitterOutput =
    (splitterOutId, callback) => async () => {
        try {
            await axiosInstance.delete(
                `/splitters/disconnect-child/${splitterOutId}`
            );
            callback();
            toast.success('Output disconnected successfully');
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };
