import { StringCaser } from "@/utils/utils";
import { findRecyclerViews } from "./recycler";

export const findComponentsWithSearchAction = (
  data,
  configuration,
  result = []
) => {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findComponentsWithSearchAction(item.components, result);
    }
    if (
      configuration?.appBar?.some(
        (bar) =>
          bar.fragment ===
          StringCaser(
            item.name,
            {
              separator: "",
              casetype: "camelCase",
            } && bar.searchActions.includes("Search")
          )
      )
    ) {
      result.push(item);
    }
  }

  return result;
};

export const generateSearchViewImports = (fragment, configuration) => {
  const searchActionFragment = configuration?.appBar?.filter((frag) =>
    frag?.selectedActions?.includes("Search")
  );

  const hasNoSearchAction =
    searchActionFragment &&
    searchActionFragment?.some((element) => {
      const formattedName = StringCaser(fragment.name, {
        separator: "",
        casetype: "camelCase",
      });
      return element.fragment === formattedName;
    });
  if (!hasNoSearchAction) return "";
  const recycler = findRecyclerViews(fragment);
  let name = StringCaser(recycler[0]?.props?.name, { casetype: "capitalize" });

  return `
    import androidx.appcompat.widget.SearchView
    // import android.view.Menu
    // import android.view.MenuInflater
    import android.view.MenuItem
    // import ${configuration.packageName}.data.${name}Model
    `;
};

export const generatesearchViewFragmentTrigger = (fragment, configuration) => {
  const searchActionFragment = configuration?.appBar?.filter(
    (frag) => frag?.selectedActions?.length > 0
  );
  const hasNoSearchAction =
    searchActionFragment &&
    searchActionFragment?.some((element) => {
      const formattedName = StringCaser(fragment.name, {
        separator: "",
        casetype: "camelCase",
      });
      return element.fragment === formattedName;
    });
  if (!hasNoSearchAction) return "";

  return `
 setHasOptionsMenu(true)
`;
};

export const generateSearchFunctions = (fragment, configuration) => {
  const searchActionFragment = configuration?.appBar?.filter((frag) =>
    frag?.selectedActions?.includes("Search")
  );
  const hasNoSearchAction =
    searchActionFragment &&
    searchActionFragment?.some((element) => {
      const formattedName = StringCaser(fragment.name, {
        separator: "",
        casetype: "camelCase",
      });
      return element.fragment === formattedName;
    });
  if (!hasNoSearchAction) return "";

  const recyclers = findRecyclerViews(fragment);

  let api = "";
  recyclers.forEach((recycler) => {
    const apiName =
      StringCaser(
        configuration?.api?.filter((a) => a.id === recycler.dataSource)[0]
          ?.name,
        { casetype: "camelCase" }
      ) ?? "";
    // Concatenate API names from all recyclers
    api += apiName;
  });

  let name = StringCaser(recyclers[0]?.props?.name, { casetype: "capitalize" });

  const apiField = configuration?.api?.find((apiItem) => {
    return StringCaser(apiItem?.name, { casetype: "camelCase" }) === api;
  });

  return `
    
    ${recyclers?.length > 0
      ? `private fun filter(text: String) {
        baasViewModel.${api}("id,desc", "1,20", "title,cs,$text", "").observe(viewLifecycleOwner) {
            when (it.status) {
                Status.ERROR -> println(it.message ?: "Something went wrong")
                Status.LOADING -> {
                    println(it.message ?: "loading")
                }

                Status.SUCCESS -> {

                    val list: List<${name}Model> = it.data?.list!!.map { map ->
                        ${recyclers[0]?.props?.fields
        .split(",")
        .map(
          (f) =>
            `val ${f} = map["${f.trim()}"]${apiField?.columns[f.trim()] == "int"
              ? `.toString() as? String ?: ""`
              : `as? String ?: ""`
            }`
        )
        .join("\n ")}

                       ${name}Model(${recyclers[0]?.props?.fields
        .split(",")
        .map(
          (f) =>
            `${f}${apiField?.columns[f.trim()] == "int"
              ? `.substringBefore(".")`
              : ``
            }`
        )
        .join(", ")})
                    }

                    adapter${name}.updateData(list)

                }
            }}
    }`
      : `private fun filter(text: String) {
        }`
    }`;
};

export const searchXML = (configuration) => {
  return `
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <item
            android:id="@+id/actionSearch"
            android:icon="@android:drawable/ic_menu_search"
            android:title="Search"
            app:actionViewClass="androidx.appcompat.widget.SearchView"
            app:showAsAction="ifRoom|collapseActionView" />

    </menu>
    `;
};
