import React from 'react';
import { useStateWithCallbackLazy } from '../../custom-hooks/statehooks';
/**
 * this hook is used for easily manage the controller and uncontrolled the selections of form component.
 * We can use it for Checkbox, MultiDropDown
 * the selected items will be added in last of array and recent accessed will changed.
 * props name should be onChange,defaultValue,  selectedValue.
 * @param {*} props = onChange,defaultValue,  selectedValue
 */

export default function useCheckboxGroupControl({onChange,defaultValue=[],selectedValue=null},customizeState=null){
    if(!selectedValue){
        let [ state , setState] = useStateWithCallbackLazy(defaultValue); 
        let onChangeWrapping = React.useCallback((value,event/*callback*/)=>{
              //Synchronous - promised
              setState((oldState)=>{
                let newState=oldState;
                if(oldState.includes(value)){
                  newState = newState || [];
                  newState = newState.filter((item)=>item!==value);
                }  
                else if(!oldState.includes(value)){
                  newState = newState || [];
                  newState = [...newState,value];                 
                }
                return customizeState ? customizeState(newState,value) :  newState;
              },(newState)=>{
                onChange && onChange(newState,event);  
                //callback && callback(value,event);
             });
             /* Asynchronous - JS doesn't work (don't wait for a line execution) like Synchronous while calling functions.
                setState(value) 
                props.onChange(value,event)
             */
        },[]);
        return [state, onChangeWrapping];
    }


    /*let onChangeWrappingDummy = React.useCallback((value,event,callback)=>{
        onChange && onChange(value,event);  
        //callback && callback(value,event);
    },[]);*/
    
    return [  selectedValue, onChange];
}

/**
 

 let [ state , setState ]  =  useMultiSelectionControl({onChange,defaultValue,  selectedValue});

 state = will array of items selected.

 setState = (state,event)=>{

 }

 */

 export const deriveValuesFromChildren = ({selectedValue,defaultValue,children}, checkCondition)=>{

  if(children && !selectedValue && !defaultValue ){

    let checkedDefaultValue=[];
    React.Children.forEach(children, (child)=>{ 
      if(child.props.checked){
        checkedDefaultValue.push(child.props.value)
      }
    });

    return { selectedValue:undefined, defaultValue : checkedDefaultValue, checkCondition: null };

  }
  

  return { selectedValue, defaultValue, checkCondition }
  

}



