import { FormGeneratorNode } from '@devsun/form-generator';
import { ObjectMetaModel } from '@devsun/form-generator/dist';
import get from 'lodash/get';

function isChildrensModelNotEmpty(
  node: FormGeneratorNode,
  model: ObjectMetaModel
): boolean {
  const childrens: FormGeneratorNode[] = node.children || [];
  let hasValues = false;

  for (let i = 0; i < childrens.length; i++) {
    const child = childrens[i];

    if (child.fieldName) {
      const modelValue = get(model, child.fieldName, undefined);

      // todo check for enum
      const hideOnFalsy = get(child, 'rawAttrs.props.hideOnFalsy', false);
      const hasVal =
        modelValue !== undefined &&
        (!hideOnFalsy || (hideOnFalsy && get(model, child.fieldName, false)));
      if (hasVal || child.enum) {
        hasValues = true;
        break;
      }
    }

    if (child.children && !hasValues) {
      hasValues = isChildrensModelNotEmpty(child, model);
    }
  }

  return hasValues;
}

// refactor this totally
function notNullishField(
  node: FormGeneratorNode,
  model: ObjectMetaModel
): boolean {
  const fieldName: string | undefined = node.fieldName || '';
  const groups = node.rootSchema.groups || [];

  const hideIfNull = !!groups.find((gr: any) => {
    const type = gr.view === 'tablegroup';
    return type && gr.attrList.includes(fieldName);
  });

  return (
    hideIfNull && model[fieldName] == undefined && model[fieldName] == null
  );
}

export { isChildrensModelNotEmpty, notNullishField };
