import { Selection } from '@assets/filters/parameters/filterDataSlice';

/**
 * A curried function used to remove a selected value
 * from all selected values of a parameter from filterData context.
 *
 * @return a callback function which produces a new filters state from the old one (with the parameter value deleted)
 */
export function removeParameterValue<T extends Selection>(parameterId: number, parameterValueId?: number) {
   if (!parameterValueId) {
      return (prev: T) => {
         const newData = { ...prev };
         if (!newData.parameters) {
            return newData;
         }

         delete newData.parameters[parameterId];

         if (!Object.keys(newData.parameters).length) {
            delete newData.parameters;
         }

         return newData;
      };
   }

   return (prev: Selection) => {
      const newData = {...prev};
      if (!newData.parameters) {
         return newData;
      }

      const id = parameterId as unknown as keyof typeof newData.parameters;
      const targetParameter = newData.parameters[id];

      if (!targetParameter || targetParameter.type !== 'list') {
         return newData;
      }

      const newSelectedValues = targetParameter.value.filter(v => v !== parameterValueId);

      if (!newSelectedValues.length) {
         delete newData.parameters[id];

         if (!Object.keys(newData.parameters).length) {
            delete newData.parameters;
         }

         return newData;
      }

      return {
         ...newData,
         parameters: {
            ...newData.parameters,
            [id]: {
               ...targetParameter,
               value: newSelectedValues,
            },
         },
      };
   };
}
