"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePropsResolution = usePropsResolution;
exports.usePropsResolutionWithComponentTheme = void 0;

var _useNativeBase = require("../useNativeBase");

var _tools = require("../../theme/tools");

var _useBreakpointResolvedProps = require("../useBreakpointResolvedProps");

var _propsFlattener = require("./propsFlattener");

var _useResponsiveSSRProps = require("../useResponsiveSSRProps");

var _NativeBaseContext = require("../../core/NativeBaseContext");

var _styled = require("../../utils/styled");

var _colorMode = require("../../core/color-mode");

var _lodash = _interopRequireDefault(require("lodash.get"));

var _reactNative = require("react-native");

var _lodash2 = _interopRequireDefault(require("lodash.merge"));

var _utils = require("../../utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* eslint-disable @typescript-eslint/no-unused-vars */
// const getThemeProps = resolvedMap.theme.getThemeProps;

/**
 * @summary Combines provided porps with component's theme props and resloves them.
 * @arg {string} component - Name of the component.
 * @arg {object} incomingProps - Props passed by the user.
 * @arg {object} state - dependent states.
 * @arg {object} config - configuration for resolution. Accepts key like ignoreProps, resolveResponsively.
 * @returns {object} Resolved and flattened props.
 */
function usePropsResolution(component, {
  INTERNAL_themeStyle,
  stateProps,
  ...inputProps
}, state, config) {
  const {
    theme
  } = (0, _useNativeBase.useNativeBase)();
  const {
    colorMode
  } = (0, _colorMode.useColorMode)();
  const providerId = (0, _NativeBaseContext.useNativeBaseConfig)('NativeBase').providerId; // need to think

  const [ignoredProps, incomingProps] = (0, _tools.extractInObject)(inputProps, ['children', 'onPress', 'onOpen', 'onClose'].concat((config === null || config === void 0 ? void 0 : config.ignoreProps) || [])); // componentThemeProps - return default+extended theme resolved props

  const componentThemeProps = (0, _styled.getThemeProps)(theme, providerId, component, {
    colorMode: colorMode,
    platform: _reactNative.Platform.OS
  }, state, incomingProps);
  const stateStyleFromProps = (0, _tools.omitUndefined)(componentThemeProps.stateStyleFromProps); // This is only for TextArea

  if (config !== null && config !== void 0 && config.extendTheme) {
    config.extendTheme.forEach(extendedComponent => {
      const extendedThemeProps = (0, _styled.getThemeProps)(theme, providerId, extendedComponent, {
        colorMode,
        platform: _reactNative.Platform.OS
      }, state, incomingProps);
      componentThemeProps.style = [...componentThemeProps.style, ...extendedThemeProps.style];
      componentThemeProps.styleFromProps = { ...componentThemeProps.styleFromProps,
        ...extendedThemeProps.styleFromProps
      };
      componentThemeProps.unResolvedProps = { ...componentThemeProps.unResolvedProps,
        ...extendedThemeProps.unResolvedProps
      };
    });
  }

  const componentTheme = (0, _lodash.default)(theme, "components.".concat(component)); // usePropsResolutionWithComponentTheme - returns inline theme props

  const resolvedPropsWithStateProps = usePropsResolutionWithComponentTheme(componentTheme, (0, _lodash2.default)({}, componentThemeProps === null || componentThemeProps === void 0 ? void 0 : componentThemeProps.unResolvedProps, incomingProps), theme, state, { ...config,
    name: component
  });
  let resolvedFlattenProps = resolvedPropsWithStateProps.flattenProps;
  const resolvedStateProps = { ...stateProps,
    ...resolvedPropsWithStateProps.stateProps
  }; // Merge default props with inline resolved props

  resolvedFlattenProps.INTERNAL_themeStyle = INTERNAL_themeStyle ? [componentThemeProps.styleFromProps, ...INTERNAL_themeStyle] : [componentThemeProps.styleFromProps];
  resolvedStateProps.INTERNAL_themeStyle = stateProps !== null && stateProps !== void 0 && stateProps.INTERNAL_themeStyle ? [stateStyleFromProps, ...stateProps.INTERNAL_themeStyle] : (0, _utils.isEmptyObj)(stateStyleFromProps) ? [] : [stateStyleFromProps]; // merge rest default props with resolved props

  resolvedFlattenProps = { ...componentThemeProps.restDefaultProps,
    ...resolvedFlattenProps
  };

  if (resolvedFlattenProps.size) {
    if (!sizesExistsInTheme(componentTheme, resolvedFlattenProps.size) && (0, _tools.isLiteral)(resolvedFlattenProps.size)) {
      resolvedFlattenProps = {
        boxSize: resolvedFlattenProps.size,
        ...resolvedFlattenProps
      };
    }

    resolvedFlattenProps.size = undefined;
  } // merge for each internal pseudo props


  for (const property in componentThemeProps.internalPseudoProps) {
    if (_styled.PSEUDO_PROP_COMPONENT_MAP[property]) {
      var _resolvedFlattenProps;

      const pseudoComponentThemeProps = (0, _styled.getThemeProps)(theme, providerId, "".concat(component, ".").concat(_styled.PSEUDO_PROP_COMPONENT_MAP[property]), {
        colorMode,
        platform: _reactNative.Platform.OS
      }, {}, incomingProps);
      resolvedFlattenProps[property] = { ...pseudoComponentThemeProps.restDefaultProps,
        ...componentThemeProps.internalPseudoProps[property],
        ...resolvedFlattenProps[property],
        INTERNAL_themeStyle: (_resolvedFlattenProps = resolvedFlattenProps[property]) !== null && _resolvedFlattenProps !== void 0 && _resolvedFlattenProps.INTERNAL_themeStyle ? [pseudoComponentThemeProps.styleFromProps, ...resolvedFlattenProps[property].INTERNAL_themeStyle] : // resolvedProps[property].INTERNAL_themeStyle.unshift(
        //     pseudoComponentThemeProps.styleFromProps
        //   )
        // [
        //     {
        //       ...pseudoComponentThemeProps.styleFromProps,
        //     },
        //     ...resolvedProps[property].INTERNAL_themeStyle,
        //   ]
        [pseudoComponentThemeProps.styleFromProps]
      };
    }
  } // for inline pseudo compoennt props- merge property


  for (const property in resolvedStateProps) {
    if (_styled.PSEUDO_PROP_COMPONENT_MAP[property]) {
      if (resolvedFlattenProps[property]) {
        resolvedFlattenProps[property].stateProps = resolvedStateProps[property];
      } else {
        resolvedFlattenProps[property] = {
          stateProps: resolvedStateProps[property]
        };
      }
    }
  }

  const resolvedProps = (0, _tools.omitUndefined)({ ...resolvedFlattenProps,
    ...ignoredProps,
    stateProps: resolvedStateProps
  });
  return resolvedProps;
}
/*Resolve all the internal used Pseudo Props*/
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars


const resolvePseudoProps = (flatPseudoProp, baseStylePseudoProp) =>
/** Props coming from Pseudo inside defaultStyles(baseStyle) */
{
  for (const prop in flatPseudoProp) {
    baseStylePseudoProp[prop] = flatPseudoProp[prop];
    /* Replace all the similar prop from from internal props */
  }

  return baseStylePseudoProp;
}; // @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars


const resolveComponentTheme = (themeType, providedTheme, theme, incomingWithDefaultProps, colorModeProps) => {
  try {
    if (themeType[1]) {
      return typeof providedTheme[themeType[0]][themeType[1]] !== 'function' ? providedTheme[themeType[0]][themeType[1]] : providedTheme[themeType[0]][themeType[1]]({
        theme,
        ...incomingWithDefaultProps,
        ...colorModeProps
      });
    } else {
      return typeof providedTheme[themeType[0]] !== 'function' ? providedTheme[themeType[0]] : providedTheme[themeType[0]]({
        theme,
        ...incomingWithDefaultProps,
        ...colorModeProps
      });
    }
  } catch {
    return {};
  }
}; // const isLiteral = (value: any) => {
//   if (typeof value === 'string' || typeof value === 'number') {
//     return true;
//   }
//   return false;
// };


const sizesExistsInTheme = (componentTheme, size) => {
  if (componentTheme !== null && componentTheme !== void 0 && componentTheme.sizes) {
    if (componentTheme.sizes[size]) {
      return true;
    }
  }

  return false;
};

const usePropsResolutionWithComponentTheme = (componentTheme, incomingProps, theme, state, config) => {
  // return incomingProps;
  // optimized-start
  const cleanIncomingProps = (0, _useResponsiveSSRProps.useResponsiveSSRProps)(incomingProps, theme); // optimized-end

  const isSSR = (0, _NativeBaseContext.useNativeBaseConfig)('NativeBase').isSSR;
  const disableCSSMediaQueries = !isSSR;
  const resolveResponsively = ['colorScheme', 'size', 'variant', ...((config === null || config === void 0 ? void 0 : config.resolveResponsively) || [])];
  const colorModeProps = (0, _colorMode.useColorMode)(); // const extendedTheme: Array<any> = [];
  // if (config?.extendTheme) {
  // config?.extendTheme.map((componentName: string) => {
  //   extendedTheme.push(get(theme, `components.${componentName}`, {}));
  // });
  // }
  // if (!isEmpty(componentTheme)) extendedTheme.push(componentTheme);
  // STEP 1: combine default props and incoming props
  // const incomingWithDefaultProps = merge(
  //   {},
  //   componentTheme.defaultProps || {},
  //   cleanIncomingProps
  // );

  let incomingWithDefaultProps = cleanIncomingProps; // TODO: size to boxSize conversion in user props

  if (incomingWithDefaultProps.size) {
    if (!sizesExistsInTheme(componentTheme, incomingWithDefaultProps.size) && (0, _tools.isLiteral)(incomingWithDefaultProps.size)) {
      incomingWithDefaultProps = {
        boxSize: incomingWithDefaultProps.size,
        ...incomingWithDefaultProps
      };
    }

    incomingWithDefaultProps.size = undefined;
  }

  if (incomingWithDefaultProps.variant) {
    incomingWithDefaultProps.variant = undefined;
  } // STEP 1.5: resolving component theme
  // extendedTheme.map((extededComponentTheme: any) => {
  //   if (extededComponentTheme.baseStyle) {
  //     combinedBaseStyle = {
  //       ...combinedBaseStyle,
  //       ...resolveComponentTheme(
  //         ["baseStyle"],
  //         extededComponentTheme,
  //         theme,
  //         incomingWithDefaultProps,
  //         colorModeProps
  //       ),
  //     };
  //   }
  //   if (incomingWithDefaultProps.variant) {
  //     if (extededComponentTheme.variants) {
  //       combinedVariantStyle = {
  //         ...combinedVariantStyle,
  //         ...resolveComponentTheme(
  //           ["variants", incomingWithDefaultProps.variant],
  //           extededComponentTheme,
  //           theme,
  //           incomingWithDefaultProps,
  //           colorModeProps
  //         ),
  //       };
  //     }
  //   }
  //   if (
  //     incomingWithDefaultProps.size &&
  //     extededComponentTheme?.sizes &&
  //     extededComponentTheme?.sizes[incomingWithDefaultProps.size]
  //   ) {
  //     if (
  //       typeof extededComponentTheme.sizes[incomingWithDefaultProps.size] ===
  //         "string" ||
  //       typeof extededComponentTheme.sizes[incomingWithDefaultProps.size] ===
  //         "number"
  //     ) {
  //       incomingWithDefaultProps.size =
  //         extededComponentTheme.sizes[incomingWithDefaultProps.size];
  //     } else {
  //       combinedSizeStyle = {
  //         ...combinedSizeStyle,
  //         ...resolveComponentTheme(
  //           ["sizes", incomingWithDefaultProps.size],
  //           extededComponentTheme,
  //           theme,
  //           incomingWithDefaultProps,
  //           colorModeProps
  //         ),
  //       };
  // incomingWithDefaultProps.size = undefined;
  //     }
  //   }
  // });
  // STEP 2: flatten them
  // if (process.env.NODE_ENV === "development" && cleanIncomingProps.debug) {
  //   /* eslint-disable-next-line */
  //   console.log(
  //     `%cFlattening incoming and Default`,
  //     "background: #4b5563; color: #FFF; font-weight: 700; padding: 2px 8px;"
  //   );
  // }
  // console.log(incomingWithDefaultProps, 'incoming with default');
  //TODO: hack
  //@ts-ignore


  let flattenProps, stateProps, specificityMap; // eslint-disable-next-line @typescript-eslint/no-unused-vars

  [flattenProps, specificityMap, stateProps] = (0, _propsFlattener.callPropsFlattener)(incomingWithDefaultProps, {}, 2, cleanIncomingProps, colorModeProps, state, flattenProps, { ...config,
    platform: _reactNative.Platform.OS
  }); // console.log(specificityMap, "*****");
  // console.log("outgoing ******", flattenProps);

  const responsiveProps = {};

  if (disableCSSMediaQueries) {
    // STEP 2.5: resolving responsive props
    resolveResponsively.map(propsName => {
      if (flattenProps[propsName]) {
        // @ts-ignore
        responsiveProps[propsName] = flattenProps[propsName];
      }
    });
  }

  if (resolveResponsively.includes('direction')) {
    const propName = 'direction';

    if (flattenProps[propName]) {
      // @ts-ignore
      responsiveProps[propName] = flattenProps[propName];
    }
  }

  const responsivelyResolvedProps = (0, _useBreakpointResolvedProps.useBreakpointResolvedProps)(responsiveProps); // const defaultSpecificity = merge(
  //   {},
  //   specificityMap,
  //   baseSpecificityMap,
  //   variantSpecificityMap,
  //   sizeSpecificityMap
  // );

  flattenProps = { ...flattenProps,
    ...responsivelyResolvedProps
  };
  flattenProps = (0, _propsFlattener.propsSpreader)({ ...flattenProps
  }, specificityMap); //tested
  // STEP 3: Pass it to baseStyle, then variant and then size and resolve them.
  // NOTE: Resoloving baseStyle
  //tested
  // STEP 4: merge
  // console.log(defaultStyles, "*******");
  // if (!isEmpty(defaultStyles)) {
  //   for (const prop in defaultStyles) {
  //     if (prop.startsWith("_") && flattenProps.hasOwnProperty(prop)) {
  //       /*Resolve all the internal used Pseudo Props*/
  //       defaultStyles[prop] = resolvePseudoProps(
  //         flattenProps[prop],
  //         defaultStyles[prop]
  //       );
  //     }
  //     delete flattenProps[prop];
  //   }
  // }
  // const defaultSpecificity = specificityMap;
  // merge(
  //   {},
  //   specificityMap,
  //   baseSpecificityMap,
  //   variantSpecificityMap,
  //   sizeSpecificityMap
  // );
  // console.log(defaultSpecificity, "h3h3h3");
  // flattenProps = propsSpreader(
  //   { ...defaultStyles, ...flattenProps },
  //   defaultSpecificity
  // );
  // STEP 5: Return

  return {
    flattenProps: (0, _tools.omitUndefined)(flattenProps),
    stateProps: (0, _tools.omitUndefined)(stateProps)
  };
};

exports.usePropsResolutionWithComponentTheme = usePropsResolutionWithComponentTheme;
//# sourceMappingURL=usePropsResolution.js.map