import React from 'react';
import styles from './styles.css';
import Select from '../../../../common/Select';
import set from 'lodash/set';
import has from 'lodash/has';
import uniq from 'lodash/uniq';
import controlTypes from '../../../../CustomMetadataForm/controlTypes';
import getControl from '../../../../../utils/getControl';

function renderConstraintForm(
  propKey,
  controlType,
  updateCustomMetadata,
  constraints,
  parsedMetadata
) {
  // retrieving the ConstraintsForm based on the controlType string/key
  const control = getControl({ name: controlType });
  const ConstraintsForm = control.type.ConstraintsForm;
  if (!ConstraintsForm) return null;

  const relevantParsedMetadata = has(parsedMetadata, ['value', propKey]) ?
    parsedMetadata.value[propKey] :
    undefined;

  const nestedConstraints = has(constraints, ['props', propKey, 'constraints']) ?
    constraints.props[propKey].constraints :
    {};

  // create an update function that simply overwrites the updated constraints
  const onUpdateConstraints = (newConstraint) => {
    console.log('constraintChanges', { ...newConstraint });
    const newCustomMetadata = {};
    console.log('newCustomMetadata', { ...newCustomMetadata });
    if (!has(newCustomMetadata, ['props', propKey])) {
      set(newCustomMetadata, ['props', propKey], {});
    }
    newCustomMetadata.props[propKey].constraints = newConstraint;
    updateCustomMetadata(newCustomMetadata);
  };

  return (
    <ConstraintsForm
      onUpdate={onUpdateConstraints}
      constraints={nestedConstraints}
      parsedMetadata={relevantParsedMetadata}
    />
  );
}

export default (props) => {
  /*
    constraints: {
      props: {
        a: …
      }
    }


    parsedMetadata: {
      value: {
        a: …
      }
    }
  */

  console.log('a', props.constraints);
  console.log('b', props.parsedMetadata);

  // retriev all propKeys from the parsed & custom metadata
  let propKeys = [];
  if (props.constraints.props) {
    propKeys = propKeys.concat(Object.keys(props.constraints.props));
  }
  if (props.parsedMetadata.value) {
    propKeys = propKeys.concat(Object.keys(props.parsedMetadata.value));
  }
  propKeys = uniq(propKeys);

  return (
    <div className={styles.wrapper}>
      {
        propKeys.map((propKey) => {
          let controlType;
          if (has(props.constraints, ['props', propKey, 'controlType'])) {
            console.log('in x');
            controlType = props.constraints.props[propKey].controlType;
          } else {
            console.log('in y');
            controlType = props.parsedMetadata.value[propKey].name;
          }
          return (
            <div key={propKey}>
              <div className={styles.propLabel}>
                {propKey}
              </div>
              <Select
                label={has(props.parsedMetadata, ['value', propKey, 'name']) ?
                 props.parsedMetadata.value[propKey].name :
                 'Not defined'}
                value={controlType}
                onChange={(event) => {
                  console.log('constraints', { ...props.constraints.props });
                  // take existing constraints.props
                  const newCustomMetadata = has(props, ['constraints', 'props']) ?
                    { ...props.constraints.props } :
                    {};

                  console.log('newCustomMetadata', { ...newCustomMetadata });
                  // set an empty object for the wanted key to
                  //  which also removes inner constraints in case they exist
                  set(newCustomMetadata, [propKey], {});
                  newCustomMetadata[propKey].controlType = event.target.value;
                  // give back the props list
                  props.onUpdate({ props: newCustomMetadata });
                }}
                options={controlTypes.map((type) => ({ value: type }))}
              />
            {renderConstraintForm(
              propKey,
              controlType,
              props.onUpdate,
              props.constraints,
              props.parsedMetadata
            )}
            </div>
          );
        })
      }
    </div>
  );
};

@@ -1066,156 +1066,48 @@
 cons
-ole.log('constraintChanges', %7B ...newConstraint %7D);%0A    const newCustomMetadata = %7B%7D;%0A    console.log('newCustomMetadata', %7B ...newCustomMetadata
+t newCustomMetadata = %7B ...constraints
  %7D
-)
 ;%0A  
@@ -1674,90 +1674,8 @@
 */%0A%0A
-  console.log('a', props.constraints);%0A  console.log('b', props.parsedMetadata);%0A%0A
   //
@@ -2199,41 +2199,8 @@
 ) %7B%0A
-            console.log('in x');%0A
     
@@ -2290,41 +2290,8 @@
 e %7B%0A
-            console.log('in y');%0A
     
@@ -2785,86 +2785,8 @@
 %3E %7B%0A
-                  console.log('constraints', %7B ...props.constraints.props %7D);%0A
     
@@ -2999,86 +2999,8 @@
 %7D;%0A%0A
-                  console.log('newCustomMetadata', %7B ...newCustomMetadata %7D);%0A
     
@@ -3502,16 +3502,18 @@
         
+  
 %7BrenderC
@@ -3527,16 +3527,18 @@
 ntForm(%0A
+  
         
@@ -3558,32 +3558,34 @@
 ,%0A              
+  
 controlType,%0A   
@@ -3587,32 +3587,34 @@
 ,%0A              
+ 
+ 
 props.onUpdate,%0A
@@ -3613,16 +3613,18 @@
 Update,%0A
+  
         
@@ -3654,32 +3654,34 @@
 ,%0A              
+  
 props.parsedMeta
@@ -3685,16 +3685,18 @@
 etadata%0A
+  
         

make sure to take existing constrains into account & cleanup