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

const CANFiltersContext = React.createContext();

export const CANFiltersProvider = ({ children }) => {
  const [busy, setBusy] = useState(false);
  const [filters, setFilters] = useState([]);
  const [totalFilters, setTotalFilters] = useState(0);

  const addFilter = async (vin, filter, token) => {
    try {
      setBusy(true);

      validateVIN(vin);
      validateFilter(filter);

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

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

      validateVIN(vin);

      const result = await api.getFilters(vin, search, token);
      if (result.error) {
        setFilters([])
        throw new Error(`Get filters error. ${result.message}`);
      }

      setFilters(result.data)
      if (result.total) {
        setTotalFilters(result.total);
      }
      return result;
    } finally {
      setBusy(false);
    }
  };

  const updateFilter = async (vin, canID, filter, token) => {
    try {
      setBusy(true);

      validateVIN(vin);
      validateFilter(filter);

      const result = await api.updateFilter(vin, canID, filter, token);
      if (result.error) {
        throw new Error(`Update filters error. ${result.message}`);
      }
      return result;
    } finally {
      setBusy(false);
    }
  }

  const deleteFilter = async (vin, canID, token) => {
    try {
      setBusy(true);

      validateVIN(vin);
      validateCANID(canID);

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

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

  return (
    <CANFiltersContext.Provider
      value={{
        busy,
        filters,
        totalFilters,
        addFilter,
        getFilters,
        updateFilter,
        deleteFilter
      }}
    >
      {children}
    </CANFiltersContext.Provider>
  );
};

export const useCANFiltersContext = () => useContext(CANFiltersContext);
