import { toast } from 'react-hot-toast';
import axiosInstance from '../../util/axiosInstance';
import { addDevice, removeDevice } from '../reducers/currentClusterReducer';

export const AddDeviceToCluster =
    (deviceInfo, callback) => async (dispatch, getState) => {
        const {
            currentClusterReducer: { currentCluster },
        } = getState();
        try {
            const { data } = await axiosInstance.post('/devices', {
                ...deviceInfo,
                cluster_id: currentCluster.id,
            });
            toast.success('Successfully Added Device');
            dispatch(addDevice(data));
            callback(data);
        } catch (error) {
            console.log(error);
        }
    };

export const updateDeviceInfo =
    (deviceId, deviceInfo, callback) => async () => {
        try {
            await axiosInstance.put(`/devices/${deviceId}`, {
                ...deviceInfo,
            });
            callback(deviceInfo);
            toast.success('Device updated successfully');
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const deleteDeviceFromCluster =
    (deviceId, callback) => async (dispatch) => {
        try {
            await axiosInstance.delete(`/devices/${deviceId}`);
            dispatch(removeDevice(deviceId));
            callback();
            toast.success('Successfully Deleted Device');
        } catch (error) {
            toast.error(error.response.data.message);
        }
    };

export const disconnectDevicePort = (portId, callback) => async () => {
    try {
        await axiosInstance.delete(`/devices/disconnect-port/${portId}`);
        callback();
        toast.success('Port disconnected successfully');
    } catch (error) {
        toast.error(error.response.data.message);
    }
};

export const portUpdate = (portId, portInfo, callback) => async () => {
    try {
        await axiosInstance.patch(`/devices/update-ports/${portId}`, {
            ...portInfo,
        });
        callback(portInfo);
        toast.success('Port updated successfully');
    } catch (error) {
        toast.error(error.response.data.message);
    }
};
