import React from "react";
import classNames from "classnames";
import { TableAddon, TableMiddleware } from "../TableProps";
import { mergeStyle } from "../../_util/merge-style";

/**
 * `stylize` 插件用于支持表格各部分的样式及类名配置。
 */
export interface StylizeOption {
  /**
   * 组件容器自定义类名
   */
  className?: string;

  /**
   * 组件容器自定义样式
   */
  style?: React.CSSProperties;

  /**
   * 表头容器自定义类名
   */
  headClassName?: string;

  /**
   * 表头容器自定义样式
   */
  headStyle?: React.CSSProperties;

  /**
   * 表格 Body 容器自定义类名
   */
  bodyClassName?: string;

  /**
   * 表格 Body 容器自定义样式
   */
  bodyStyle?: React.CSSProperties;
}

export function stylize({
  className,
  style,
  headClassName,
  headStyle,
  bodyClassName,
  bodyStyle,
}: StylizeOption): TableAddon {
  const addon: TableAddon = { getInfo: () => ({ name: "stylize" }) };

  if (className || style) {
    addon.onInjectTable = withStyle(className, style);
  }
  if (headClassName || headStyle) {
    addon.onInjectHead = withStyle(headClassName, headStyle);
  }
  if (bodyClassName || bodyStyle) {
    addon.onInjectBody = withStyle(bodyClassName, bodyStyle);
  }

  return addon;
}

function withStyle(
  className: string,
  style: React.CSSProperties
): TableMiddleware<(...args: any[]) => JSX.Element> {
  return render => (...args) => {
    const element = render(...args);
    const elementProps = element.props;
    return React.cloneElement(element, {
      className: classNames(elementProps.className, className),
      style: mergeStyle(elementProps.style, style),
    });
  };
}
