import React from 'react';
import SkeletonThemeWrapper from "../../customization-cornor/skeletonCustomization";
import useCheckboxControl,{ deriveValuesFromChildren } from "./Checkbox.reducer";
import CheckboxContext from "./CheckboxGroupContext";

const checkCondition = (currentValue=null,selectedValue=[])=>{
  return (selectedValue||[]).includes(currentValue);
};

const onChangeCallbackHandler = (onChange,itemOnChange)=>{
  if(!itemOnChange){
    return onChange;
  }
  return (value,event)=>{
    onChange && onChange(value,event);
    itemOnChange && itemOnChange(value,event);
  }
};

export function CheckboxGroupBehaviour(props){
    //let { selectedValue: propSelectedValue, defaultValue: propDefaultValue, checkCondition: propCheckCondition } = deriveValuesFromChildren(props,checkCondition);

    const [selectedValue,onChange] = useCheckboxControl(props);
    //   {
    //   selectedValue: propSelectedValue,
    //   defaultValue: propDefaultValue,
    //   onChange: props.onChange
    // });
    let renderProps = { selectedValue,onChange, onChangeCallbackHandler, checkCondition };
    let { renderComponent, ...basicProps} = props;
    return <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />;
}

export function CheckboxContextBehaviour(props){
  const [selectedValue,onChange] = useCheckboxControl(props);
  let renderProps = { selectedValue, onChange, onChangeCallbackHandler, checkCondition  };
  let { renderComponent, ...basicProps} = props;
  return <CheckboxContext.Provider value={{ 
    selectedValue:(selectedValue?selectedValue:props.defaultValue ?props.defaultValue :[]),
    onChange,
    name : props.name
    }}> 
   <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />
</CheckboxContext.Provider>
  
}

export default function CheckboxBehaviour(props){
    let  { selectedValue,onChange:onChangeWrapping,name,checkCondition:checkConditionProp } =props// React.useContext(CheckboxContext) || {onChange:props.onChange?props.onChange:{}};
    let checkboxContext = React.useContext(CheckboxContext);
    if(checkboxContext){
      selectedValue = checkboxContext.selectedValue;
      name = checkboxContext.name;
      onChangeWrapping = props.onChange ? (value,event)=>{
        checkboxContext.onChange && checkboxContext.onChange(value,event);
        props.onChange && props.onChange(value,event);
      } : checkboxContext.onChange;
      checkConditionProp = checkCondition;
    }
    let renderProps = { 
      selectedValue,
      name, 
      onChange:onChangeWrapping,
      checkCondition:checkConditionProp
    };
    let { renderComponent, ...basicProps} = props;
    return <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />;
}