import toast from 'react-hot-toast';
import axiosInstance from '../../util/axiosInstance';
import { setCables, addCable, removeCable } from '../reducers/cableReducer';

export const fetchCables = () => async (dispatch) => {
    try {
        const { data } = await axiosInstance.get('/cables');
        dispatch(setCables(data));
    } catch (error) {
        console.log(error);
    }
};

export const addNewCable =
    (cableInfo, callback) => async (dispatch, getState) => {
        const {
            coordinatesReducer: { startNode, endNode, coordinates },
        } = getState();

        const requestInfo = {
            ...cableInfo,
            coordinates,
            startNode,
            endNode,
        };

        try {
            const { data } = await axiosInstance.post('/cables', requestInfo);
            dispatch(addCable(data));
            callback(data);
        } catch (error) {
            console.log('this is error', error);
        }
    };

export const deleteCableMap = (cableId, callback) => async (dispatch) => {
    try {
        await axiosInstance.delete(`/cables/${cableId}`);
        dispatch(removeCable(cableId));
        callback();
        toast.success('Cable Deleted');
    } catch (error) {
        console.log(error);
    }
};

export const disconnectFiber = (fiberId, callback) => async () => {
    try {
        await axiosInstance.delete(`cables/disconnect-fiber/${fiberId}`);
        toast.success('Fiber Disconnected');
        callback();
    } catch (error) {
        console.log(error);
    }
};
