import { StringCaser } from "@/utils/utils";
import {
  filterApiById,
  findComponentsWithNameFields,
  findComponentsWithSubmitAction,
  underscoreToPascalCase,
} from "./form";
import { getComponentViewBindingId } from "./helpers";

export const generateSubmitActionFunction = (fragment, configuration) => {
  if (findComponentsWithSubmitAction(fragment).length == 0) return "";
  const api = filterApiById(fragment, configuration, "to");
  let fields = api?.inputs;

  let newField = [];
  let allNewField = [];
  fields?.map((field) => {
    let formatedField = underscoreToPascalCase(field.name);

    let formattedType =
      field.dataType === "Integer?" && field.name !== "user_id"
        ? `${formatedField}.toInt()`
        : formatedField;

    allNewField.push(formattedType);
    newField.push(formatedField);
  });

  let nonEmptyFieldsCheck =
    newField
      .filter((field) => field !== "id" && field !== "userId")
      .join(".isNotEmpty() && ") + ".isNotEmpty()";

  const hasId = newField.includes("id");

  let allFields = allNewField
    .filter((field) => field !== "id.toInt()")
    .concat(hasId ? "id.toInt()" : "")
    .join(", ");

  let button = findComponentsWithSubmitAction(fragment);
  let textField = findComponentsWithNameFields(fragment);

  let content = [];
  for (const element of button) {
    content.push(`
          binding.${getComponentViewBindingId(element)}.setOnClickWithDebounce {
                if (${nonEmptyFieldsCheck}) ${StringCaser(fragment.name, {
      separator: "",
      casetype: "camelCase",
    })}(${allFields})
            else snackBar(getString(R.string.empty_location))
            }
           ${textField
             .map((text) => {
               `binding.${getComponentViewBindingId(
                 text
               )}.doAfterTextChanged {${StringCaser(text.props.name, {
                 separator: "",
                 casetype: "camelCase",
               })} = it.toString() }`;
             })
             .join("\n")}
      `);
  }
  return content.join("\n");
};
