import { generateComponentId } from "./helpers";

function findCheckboxComponents(data, result = []) {
  if (!Array.isArray(data)) data = [data];
  for (const item of data) {
    if ("components" in item) {
      findCheckboxComponents(item.components, result);
    }
    if ("children" in item) {
      findCheckboxComponents(item.children, result);
    }
    if (item.name === "CheckBox") {
      result.push(item);
    }
  }

  return result;
}

export const checkboxImport = (fragment) => {
  if (findCheckboxComponents(fragment).length == 0) return "";
  return `
    import android.widget.CheckBox
import android.widget.CompoundButton
`;
};

export const buildCheckboxBinding = (fragment) => {
  if (findCheckboxComponents(fragment).length == 0) return "";

  const checkBox = findCheckboxComponents(fragment);
  return `
    ${checkBox
      .map(
        (element) => `
          val ${element.props.name} = view.findViewById<CheckBox>(R.id.${generateComponentId(element)})

        ${element.props.name}.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { _, isChecked ->
                if (isChecked) "1" else "0"
            })
        `
      ).join("\n")}`;
};
