import React from 'react';
import {  TemplateDefinition } from '../models';




export const NodeTemplate = (props) => {
  // const [activeNode, setActiveNode] = useState({} as ActiveNode);
  const {activeNode} = props.manifest;

    // useEffect(() => {
    //     const nodeSub = props.store.query('manifest.activeNode')
    //     .pipe(skipWhile(x => !x))
    //     .subscribe(setActiveNode);
    //     return () => {
    //         nodeSub.unsubscribe();
    //     };
    // });
    let RenderTemplate;
    if (activeNode) {
      // COMPONENT AS STRING
      if (activeNode && typeof activeNode.component === 'function') {
          const Component = activeNode.component;
         RenderTemplate = (
           <Component {...activeNode.inputs} {...props} />
         );
  
      } else {
        // COMPONENTS AS TEMPLATE DEFINITION
          let organisms: {component: any, inputs: any, outputs: any}[] = [];
              organisms = (activeNode.component as TemplateDefinition).children.map((def) => {
                  const inps = def.inputs || {};
                  const outs = def.outputs || {};
                  const localInputs = Object.entries({...activeNode.inputs, ...inps}).reduce((acc, [prop, value]: [string, any]) => {
                    if (!prop.endsWith('$')) {
                      return {
                        ...acc,
                        [prop]: value,
                      };
                    }
                    return {
                      ...acc,
                      [prop]: props.store.query(value),
                    };
                  }, {});
                  const localOutputs = Object.entries({...activeNode.outputs, ...outs}).reduce((acc, [prop, value]: [string, any]) => {
                    return {
                      ...acc,
                      [prop]: value  // function
                    };
                  }, {});
                  return {
                    component: def.component,
                    inputs: localInputs,
                    outputs: localOutputs // {...props.nodeOutputs, ...outs }
                  };
                });
      
         RenderTemplate = (
          <>
            {organisms.map((organism, idx) => (
                <organism.component key={idx} {...organism.inputs} {...organism.outputs} {...props}/>
            ))}
          </>
        );
  
      }
    } else {
      RenderTemplate = <></>
    }

  return RenderTemplate;
};

