import React,{useContext} from 'react';
import SkeletonThemeWrapper from "../../customization-cornor/skeletonCustomization";
import useSelectionControl from "../../custom-hooks/useSelectionControl";
import RadioContext from "./RadioGroupContext";
import usefocusVisible from '../../accessibility-utils/focusVisible';

/**
 * To check equal condition of logic of Radio checked
 * @param {*} currentValue 
 * @param {*} selectedValue 
 * @returns 
 */
const radioCondition = (currentValue,selectedValue)=>{
  return currentValue === selectedValue;
};

/**
* To handle the item-onChange-Callback and group-onChangeCallback in skeleton 
* @param {*} onChange 
* @param {*} itemOnChange 
* @returns 
*/
const onChangeCallbackHandler = (onChange,itemOnChange)=>{
  if(!itemOnChange){
    return onChange;
  }
  return (value,event)=>{
    onChange && onChange(value,event);
    itemOnChange && itemOnChange(value,event);
  }
};

export default function RadioGroupBehaviour(props){
  const [selectedValue,onChange] = useSelectionControl(props,props.reducer);
  let renderProps = { selectedValue, onChange, onChangeCallbackHandler, radioCondition  };
  let { renderComponent, ...basicProps} = props;
    return <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />;
}

export function RadioContextBehaviour(props){
  const [selectedValue,onChange] = useSelectionControl(props,props.reducer);
 
  let { renderComponent,name,defaultValue, ...basicProps} = props;
  let renderProps = { selectedValue, onChange, name };

  return <RadioContext.Provider value={{ 
    selectedValue:(selectedValue || defaultValue),
    onChange,
    name 
    }}> 
   <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />
</RadioContext.Provider>
  
}

export function RadioBehaviour(props){
  let { selectedValue, name, onChange: onChangeWrapping, radioCondition: radioConditionProp  } = props;
  let { focusVisible,focusProps } = usefocusVisible(props);
  let radioContext = useContext(RadioContext);
  if(radioContext){
    selectedValue = radioContext.selectedValue;
    name = radioContext.name;
    onChangeWrapping = props.onChange ? (value,event)=>{
      radioContext.onChange && radioContext.onChange(value,event);
      props.onChange && props.onChange(value,event);
    } : radioContext.onChange;
    radioConditionProp = radioCondition;
  }
 
  let renderProps = { selectedValue,name, onChange:onChangeWrapping, radioCondition: radioConditionProp,focusVisible,focusProps };
  let { renderComponent, ...basicProps} = props;
  return <SkeletonThemeWrapper basicProps={basicProps} renderProps={renderProps} component={renderComponent} />;
}