import React, { useContext, useState } from "react";
import api from "../../services/fleetsAPI";
import { validateCANID, validateFilter, validateVIN } from "../../utils/validationSupplier";

const FleetContext = React.createContext();

export const FleetProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);

  const [fleet, setFleet] = useState({});

  const [fleets, setFleets] = useState([]);
  const [totalFleets, setTotalFleets] = useState(0);

  const [fleetVehicles, setFleetVehicles] = useState([]);
  const [totalFleetVehicles, setTotalFleetVehicles] = useState(0);

  const [fleetCANFilters, setFleetCANFilters] = useState([]);
  const [totalFleetCANFilters, setTotalFleetCANFilters] = useState(0);

  const addFleet = async (f, token) => {
    try {
      setBusy(true);
      validateFleet(f);

      const result = await api.addFleet(f, token);
      if (result.error) throw new Error(`Add fleet error. ${result.message}`);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const getFleet = async (name, token) => {
    try {
      setBusy(true);
      validateFleetName(name);

      const result = await api.getFleet(name, token);
      if (result.error) {
        setFleet({});
        throw new Error(`Get fleet error. ${result.message}`);
      }

      setFleet(result);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const getFleets = async (search, token) => {
    try {
      setBusy(true);

      const result = await api.getFleets(search, token);
      if (result.error) {
        setFleets([])
        throw new Error(`Get fleets error. ${result.message}`);
      }
      setFleets(result.data)
      if (result.total) {
        setTotalFleets(result.total);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const updateFleet = async (name, f, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateFleet(f);

      const result = await api.updateFleet(name, f, token);
      if (result.error) {
        throw new Error(`Update fleet error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const deleteFleet = async (name, token) => {
    try {
      setBusy(true);

      validateFleetName(name);

      const result = await api.deleteFleet(name, token);
      if (result.error) {
        throw new Error(`Delete filter error. ${result.message}`);
      }

      return result;
    } finally {
      setBusy(false);
    }
  };

  const getFleetVehicles = async (name, search, token) => {
    try {
      setBusy(true);

      const result = await api.getFleetVehicles(name, search, token);
      if (result.error) {
        setFleetVehicles([])
        throw new Error(`Get fleet vehicles error. ${result.message}`);
      }

      setFleetVehicles(result.data)
      if (result.total) {
        setTotalFleetVehicles(result.total);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const addFleetVehicle = async (name, vehicle, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateVIN(vehicle.vin);

      const result = await api.addFleetVehicle(name, vehicle, token);
      if (result.error) {
        throw new Error(`Add fleet vehicle error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const deleteFleetVehicle = async (name, vehicle, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateVIN(vehicle.vin);

      const result = await api.deleteFleetVehicle(name, vehicle, token);
      if (result.error) {
        throw new Error(`Delete fleet vehicle error. ${result.message}`);
      }

      const index = fleetVehicles.findIndex(element => element === vehicle.vin);
      if (index >= 0) fleetVehicles.splice(index, 1);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const getFleetCANFilters = async (name, search, token) => {
    try {
      setBusy(true);

      const result = await api.getFleetCANFilters(name, search, token);
      if (result.error) {
        setFleetCANFilters([])
        throw new Error(`Get fleet filters error. ${result.message}`);
      }

      setFleetCANFilters(result.data)
      if (result.total) {
        setTotalFleetCANFilters(result.total);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const addFleetCANFilter = async (name, filter, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateFilter(filter);

      const result = await api.addFleetCANFilter(name, filter, token);
      if (result.error) {
        throw new Error(`Add fleet CAN filter error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  }

  const updateFleetCANFilter = async (name, can_id, filter, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateFilter(filter);

      const result = await api.updateFleetCANFilter(name, can_id, filter, token);
      if (result.error) {
        throw new Error(`Update fleet CAN filter error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  }

  const deleteFleetCANFilter = async (name, can_id, token) => {
    try {
      setBusy(true);

      validateFleetName(name);
      validateCANID(can_id);

      const result = await api.deleteFleetCANFilter(name, can_id, token);
      if (result.error) {
        throw new Error(`Delete fleet vehicle error. ${result.message}`);
      }

      const index = fleetCANFilters.findIndex(element => element.can_id === can_id);
      if (index >= 0) fleetCANFilters.splice(index, 1);
      return result;
    } finally {
      setBusy(false);
    }
  };

  return (
    <FleetContext.Provider
      value={{
        busy,

        fleet,
        fleets,
        totalFleets,
        addFleet,
        getFleet,
        getFleets,
        updateFleet,
        deleteFleet,

        fleetVehicles,
        totalFleetVehicles,
        getFleetVehicles,
        addFleetVehicle,
        deleteFleetVehicle,

        fleetCANFilters,
        totalFleetCANFilters,
        getFleetCANFilters,
        addFleetCANFilter,
        updateFleetCANFilter,
        deleteFleetCANFilter
      }}
    >
      {children}
    </FleetContext.Provider>
  );
};

const validateFleet = (f) => {
  if (f == null) {
    throw new Error("No fleet data");
  }

  validateFleetName(f.name);
}

const validateFleetName = (name) => {
  if (name == null || !/^[\w-]+$/.test(name)) {
    throw new Error("Invalid name");
  }
};

export const useFleetContext = () => useContext(FleetContext);
