import { resolveResource } from "@tauri-apps/api/path";
import { readTextFile } from "@tauri-apps/api/fs";
import { invoke } from '@tauri-apps/api/tauri'
import "./App.css";

const codes = JSON.parse(await readTextFile(await resolveResource("resources/codes.json")));
type Code = {
  code: number;
  type: string;
  text: string;
};
const droneId = 4661;

function App() {

  const getSubjects = (input: Array<Code>) => {
    let subjects: Array<string> = [];
    input.forEach((code: Code) => {
      if (!subjects.includes(code.type)) {
        subjects.push(code.type)
      }
    });
    return subjects;
  };

  const handleClick = (type: string) => {
    let filtered = codes.filter((code: Code) => code.type === type);
    if (filtered.length == 1) {
      let assembledStr: string = droneId.toString();
      let code: string = filtered[0].code;
      if (filtered[0].code < 10) {
        code = "00" + code;
      }else if (filtered[0].code < 100) {
        code = "0" + code;
      }
      assembledStr += " :: Code " + code;
      assembledStr += " :: " + type;
      if (filtered[0].text != "."){
        assembledStr += " :: " + filtered[0].text;
      }
      console.log(assembledStr);
      invoke('type_str', {input: assembledStr});
    }else{
      // Open Submenu for type
    }
  };

  return (
    <div className="container">
      {getSubjects(codes).map((type: string, index: number) => {
        let dispType: string = type;
        let filtered = codes.filter((code: Code) => code.type === type);
        if (filtered.length == 1) {
          dispType += ((filtered[0].text == "")?" :: ...":((filtered[0].text == ".")?"":(" :: "+filtered[0].text)));
        }
        return (
          <input
            className="row"
            key={index}
            type="button"
            onClick={() =>  {
              handleClick(type)
            }}
            value={dispType}
            />
        );
      })}
    </div>
  );
}

export default App;
