import { StringCaser } from "@/utils/utils";

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

  return result;
};

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

  const hasSearchAction = searchActionFragment&&searchActionFragment?.some((element) => {
    const formattedName = StringCaser(fragment.name, {
      separator: "",
      casetype: "camelCase",
    });
    return element.fragment === formattedName;
  });

  return `
  
       override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {

        val inflater = inflater

       ${hasCartAction ? `inflater.inflate(R.menu.cart_menu, menu)` : ""}

       ${
         hasSearchAction
           ? `
        inflater.inflate(R.menu.search_menu, menu)

        val searchItem: MenuItem = menu.findItem(R.id.actionSearch)
   
        val searchView: SearchView = searchItem.getActionView() as SearchView

        searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener,
            android.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(p0: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(msg: String): Boolean {
              
                filter(msg)
                return false
            }
        })
        //return true`
           : ""
       }
    }`;
};

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

  return `
    // import android.view.Menu
    // import android.view.MenuInflater
    import android.view.MenuItem
    `;
};
