import React, { useContext } from "react";
import "../../components/library.all.module.css";
import UCLContext from "./uclContext";
import uclProviderPropTypes from "./UCLProvider.propTypes";

let getModeClassName=(mode)=>{
  return `lib-mode-${mode}`;
}

let getThemeClassName=(theme)=>{
  return `lib-theme-${theme}`;
}

const defaultFontBaseSizeName="--lib_base_textsize";

const defaultConfiguration={

    "configuration"  : {
      "--lib_base_textsize" :  16
    }
  
};


const renderGlobalVariables = (configuration)=>{

      return Object.keys(configuration).map((variableName, index)=>{

          return `${variableName} : ${configuration[variableName]};`;

      }).join('\n');

}

// overriding the public library variables
// let styleTag = global.document.getElementById("zoho-desk-ucl-variables");
// We need to handle and check nested use case of theme provider... like material ui
/**
 * @param {*} props 
 * @returns
 */
export default function UCLProvider(props){

  let themeInfo = { ...defaultConfiguration , ...(props.value || {}) };

  let variableNameClassName = `.${getModeClassName(props.mode)}.${getThemeClassName(props.theme)}`;

  let docsFontStyle = '';
  if(__DOCS__){
    docsFontStyle =  `
      html.isRem{
        font-size: ${themeInfo.configuration[defaultFontBaseSizeName]}px;
      }
   `
  }

  return (
    <UCLContext.Provider value={props.value}>
      <div className={`${getModeClassName(props.mode)} ${getThemeClassName(props.theme)} ${props.customClassName||''}`}>
        <style id="zoho-desk-ucl-variables">{`
                  ${variableNameClassName} {
                    ${renderGlobalVariables(themeInfo.configuration)}
                  }
                 ${docsFontStyle}
              `}</style>
              
        {props.children}
      </div>
    </UCLContext.Provider>
  );
}

UCLProvider.propTypes = uclProviderPropTypes;

export { UCLContext };

export const useTheme = () => {
 return useContext(UCLContext);
};

export const useThemeByComponent=(componentName)=>{

  let themeContextValue = useContext(UCLContext);
  return (themeContextValue && themeContextValue.components && themeContextValue.components[componentName]);

}