import toast from 'react-hot-toast';
import axiosInstance from '../../util/axiosInstance';
import {
    addOnu,
    removeOnu,
    updateOnu,
} from '../reducers/currentClusterReducer';

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

        try {
            const { data } = await axiosInstance.post('/onus', {
                ...onuInfo,
                cluster_id: currentCluster.id,
            });
            dispatch(addOnu(data));
            callback(data);
            toast.success('Onu added successfully');
        } catch (error) {
            toast.error('Onu not added');
        }
    };

export const updateOnuInCluster =
    (onuId, onuInfo, callback) => async (dispatch) => {
        try {
            const { data } = await axiosInstance.put(`/onus/${onuId}`, onuInfo);
            dispatch(updateOnu(data));
            callback(data);
            toast.success('Onu updated successfully');
        } catch (error) {
            toast.error('Onu not updated');
        }
    };

export const deleteOnuFromCluster = (onuId, callback) => async (dispatch) => {
    try {
        await axiosInstance.delete(`/onus/${onuId}`);
        dispatch(removeOnu(onuId));
        callback();
        toast.success('Onu deleted');
    } catch (error) {
        toast.error('Onu not deleted');
    }
};

export const disconnectOnuInterface =
    (interfaceType, onuId, callback) => async () => {
        try {
            const response = await axiosInstance.delete(
                `/onus/disconnect/${onuId}`,
                {
                    data: {
                        type: interfaceType,
                    },
                }
            );

            console.log(response);
            callback();
            toast.success('Onu disconnected');
        } catch (error) {
            toast.error('Onu not disconnected');
        }
    };
