import React from "react";
import { useState } from "react";
import { Grammar } from "../types";
export function Searches({
  setFilteredGrammars,
  grammars,
}: {
  setFilteredGrammars: React.Dispatch<React.SetStateAction<Grammar[] | null>>;
  grammars: Grammar[];
}) {
  const [rootSearch, setRootSearch] = useState(false);
  const [rootQuery, setRootQuery] = useState("");
  const [uriQuery, setUriQuery] = useState("");
  const changeSearch = () => {
    setRootQuery("");
    setUriQuery("");
    setRootSearch(!rootSearch);
    setFilteredGrammars(null);
  };

  const findByRoot = (root: string) => {
    setRootQuery(root);
    if (root.length === 0) {
      setFilteredGrammars(null);
    }
    setFilteredGrammars(
      grammars.filter(
        (grammar) =>
          grammar.rootRule &&
          grammar.rootRule.leftSymbol !== null &&
          (grammar.rootRule.leftSymbol.startsWith("<" + root) ||
            grammar.rootRule.leftSymbol.startsWith(root))
      )
    );
  };

  const findByUri = (uri: string) => {
    setUriQuery(uri);
    if (uri.length === 0) {
      setFilteredGrammars(null);
    }
    setFilteredGrammars(
      grammars.filter((grammar) => grammar.uri.startsWith(uri))
    );
  };
  return (
    <p className="fullWidth">
      {" "}
      <button className="fullWidth" onClick={changeSearch}>
        {" "}
        {rootSearch ? "URI SEARCH" : "ROOT SEARCH"}
      </button>
      <input
        className="fullWidth transparent"
        placeholder={"Search by " + (rootSearch ? "root rule" : "uri")}
        id="rootSearch"
        value={rootSearch ? rootQuery : uriQuery}
        onChange={(e) =>
          rootSearch ? findByRoot(e.target.value) : findByUri(e.target.value)
        }
      />
    </p>
  );
}
