import { StringCaser } from "@/utils/utils";
import { convertToFunctionName, underscoreToPascalCase } from "./form";

export function findLayoutWithDataSourceProperty(data, result = []) {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findLayoutWithDataSourceProperty(item.components, result);
    }
    if ("children" in item) {
      findLayoutWithDataSourceProperty(item.children, result);
    }
    if ("props" in item && item.type == "layout" && item.dataSource) {
      result.push(item);
    }
  }
  return result;
}

export const buildLayoutDataSourcefunction = (fragment, configuration) => {
  if (findLayoutWithDataSourceProperty(fragment)?.length == 0) return "";
  const dataSource = findLayoutWithDataSourceProperty(fragment);

  const content = [];
  for (const source of dataSource) {
    const api = configuration.api.find(
      (apiItem) => apiItem.id === source.dataSource
    );

    let fields = api?.inputs;

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

      let formattedType = field?.dataType === "Integer?" ? "Int?" : "String?";

      allField.push(formatedField);
      newField.push(`${formatedField}: ${formattedType}`);
    });

    content.push(`
    private fun ${convertToFunctionName(fragment.name)}(${newField}) {
        requireActivity().hideSoftKeyboard()
        baasViewModel.${StringCaser(api?.name, {
          casetype: "camelCase",
        })}(${allField}).observe(viewLifecycleOwner) {
            when (it.status) {
                Status.ERROR -> snackBar(it.message ?: getString(R.string.something_went_wrong))
                Status.LOADING -> {
                    snackBar("Loading...")
                }

                Status.SUCCESS -> {
                    snackBar("Success...")

                    val data = it.data
                    data?.let { it1 -> it1.message?.let { it2 -> Log.d("", it2) } }
                    
                }
            }
        }
    }   
`);
    return content.join("\n");
  }
};
