/**
   * @param args the command line arguments
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {

    if (args.length == 0) {
      fail();
    }
    OpenCVJNILoader.load(); // Loads the OpenCV JNI (java native interface)
    //		File servo =
    // ScriptingEngine.fileFromGit("https://github.com/NeuronRobotics/BowlerStudioVitamins.git",
    //							"BowlerStudioVitamins/stl/servo/smallservo.stl");
    //
    //		ArrayList<CSG>  cad = (ArrayList<CSG>
    // )ScriptingEngine.inlineGistScriptRun("4814b39ee72e9f590757", "javaCad.groovy" , null);
    //		System.out.println(servo.exists()+" exists: "+servo);

    boolean startLoadingScripts = false;
    Object ret = null;
    for (String s : args) {
      if (startLoadingScripts) {
        try {

          ret = ScriptingEngine.inlineFileScriptRun(new File(s), null);
        } catch (Error e) {
          e.printStackTrace();
          fail();
        }
      }
      if (s.contains("script") || s.contains("-s")) {
        startLoadingScripts = true;
      }
    }
    startLoadingScripts = false;

    for (String s : args) {

      if (startLoadingScripts) {
        try {
          ret = ScriptingEngine.inlineFileScriptRun(new File(s), (ArrayList<Object>) ret);
        } catch (Error e) {
          e.printStackTrace();
          fail();
        }
      }
      if (s.contains("pipe") || s.contains("-p")) {
        startLoadingScripts = true;
      }
    }
    boolean runShell = false;
    ShellType shellTypeStorage = ShellType.GROOVY;
    for (String s : args) {

      if (runShell) {
        try {
          shellTypeStorage = ShellType.getFromSlug(s);
        } catch (Exception e) {
          shellTypeStorage = ShellType.GROOVY;
        }
        break;
      }
      if (s.contains("repl") || s.contains("-r")) {
        runShell = true;
      }
    }

    System.out.println("Starting Bowler REPL in langauge: " + shellTypeStorage.getNameOfShell());
    // sample from
    // http://jline.sourceforge.net/testapidocs/src-html/jline/example/Example.html

    if (!Terminal.getTerminal().isSupported()) {
      System.out.println("Terminal not supported " + Terminal.getTerminal());
    }
    // Terminal.getTerminal().initializeTerminal();

    ConsoleReader reader = new ConsoleReader();
    reader.addTriggeredAction(
        Terminal.CTRL_C,
        e -> {
          System.exit(0);
        });

    if (!historyFile.exists()) {
      historyFile.createNewFile();
      reader.getHistory().addToHistory("println SDKBuildInfo.getVersion()");
      reader.getHistory().addToHistory("for(int i=0;i<100;i++) { println dyio.getValue(0) }");
      reader.getHistory().addToHistory("dyio.setValue(0,128)");
      reader.getHistory().addToHistory("println dyio.getValue(0)");
      reader
          .getHistory()
          .addToHistory(
              "ScriptingEngine.inlineGistScriptRun(\"d4312a0787456ec27a2a\", \"helloWorld.groovy\" , null)");
      reader
          .getHistory()
          .addToHistory(
              "DeviceManager.addConnection(new DyIO(ConnectionDialog.promptConnection()),\"dyio\")");
      reader
          .getHistory()
          .addToHistory(
              "DeviceManager.addConnection(new DyIO(new SerialConnection(\"/dev/DyIO0\")),\"dyio\")");
      reader.getHistory().addToHistory("BowlerKernel.speak(\"Text to speech works like this\")");
      reader.getHistory().addToHistory("println \"Hello world!\"");
      writeHistory(reader.getHistory().getHistoryList());
    } else {
      List<String> history = loadHistory();
      for (String h : history) {
        reader.getHistory().addToHistory(h);
      }
    }
    reader.setBellEnabled(false);
    reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true)));

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {

                writeHistory(reader.getHistory().getHistoryList());
              }
            });

    // SpringApplication.run(SpringBowlerUI.class, new String[]{});

    String line;
    try {
      while ((line = reader.readLine("Bowler " + shellTypeStorage.getNameOfShell() + "> "))
          != null) {
        if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) {
          break;
        }
        if (line.equalsIgnoreCase("history") || line.equalsIgnoreCase("h")) {
          List<String> h = reader.getHistory().getHistoryList();
          for (String s : h) {
            System.out.println(s);
          }
          continue;
        }
        if (line.startsWith("shellType")) {
          try {
            shellTypeStorage = ShellType.getFromSlug(line.split(" ")[1]);
          } catch (Exception e) {
            shellTypeStorage = ShellType.GROOVY;
          }
          continue;
        }
        try {
          ret = ScriptingEngine.inlineScriptStringRun(line, null, shellTypeStorage);
          if (ret != null) System.out.println(ret);
        } catch (Error e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }