/**
 * Created by baoyinghai on 7/3/17.
 */
import React from 'react';
import Generator from '../generator';
import FieldTransformers from './fieldTransformer';

const propsFilter = props => {
  return props;
};

const getDataPath = dataSource => f => {
  if (!dataSource) return null;
  const fieldDesc = dataSource[f];
  return fieldDesc.value.split('.');
};

const createNode = node => {
  const ret = {};
  if (!node) return null;
  if (Generator[node.nodeType]) {
    // 区分容器还是组件
    ret.key = node.key;
    const Comp = Generator[node.nodeType][node.name];
    const fieldHandler = getDataPath(node.dataSource);
    ret.renderComp = (data, appendProps = {}) => {
      let dataSource = null;
      if (node.nodeType !== 'CONTAINER') {
        if (data && data.split) {
          // array
          dataSource = node.dataSource && data.map(d => {
            return Object.keys(node.dataSource).reduce((obj, key) => {
              obj[key] = FieldTransformers[node.dataSource[key].vType](d, node.dataSource[key]);
              return obj;
            }, {});
          });
        } else {
          dataSource = node.dataSource && Object.keys(node.dataSource).reduce((obj, key) => {
            obj[key] = FieldTransformers[node.dataSource[key].vType](data, node.dataSource[key]);
            return obj;
          }, {});
        }
      }

      return (<Comp {...propsFilter(node.props)} {...appendProps} _getDataPath={fieldHandler} fieldDesc={node.dataSource} dataSource={dataSource} />);
    };
  }
  if (node.childrenNode) {
    ret.childrenNode = node.childrenNode.map(n => createNode(n));
  }
  return ret;
};


export default {
  ngtCreate: art => createNode(art)
};
