/*
   * (non-Javadoc)
   *
   * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
   */
  @Override
  public void keyPressed(KeyEvent keyEvent) {

    switch (keyEvent.getKeyCode()) {

        // The next selected element will be the previous node in the tree
      case KeyEvent.VK_UP:
        setFocusEditorFile(
            AcideMainWindow.getInstance()
                .getExplorerPanel()
                .getTree()
                .getPathForRow(
                    AcideMainWindow.getInstance().getExplorerPanel().getTree().getLeadSelectionRow()
                        - 1));
        break;

        // The next selected element will be the next node in the tree
      case KeyEvent.VK_DOWN:
        setFocusEditorFile(
            AcideMainWindow.getInstance()
                .getExplorerPanel()
                .getTree()
                .getPathForRow(
                    AcideMainWindow.getInstance().getExplorerPanel().getTree().getLeadSelectionRow()
                        + 1));
        break;

        // The next selected element is the current one
      case KeyEvent.VK_ENTER:
        setFocusEditorFile(
            AcideMainWindow.getInstance().getExplorerPanel().getTree().getSelectionPath());
        break;
    }
  }
  /**
   * Sets the focus into the editor file determined by the selected node given as a parameter.
   *
   * @param currentSelection Selected node in the explorer tree.
   */
  private void setFocusEditorFile(TreePath currentSelection) {

    // If there is a selected node
    if (currentSelection != null) {

      // Gets the file path from the selected node in the explorer tree
      String filePath = currentSelection.getLastPathComponent().toString();

      // Updates the status message in the status bar
      AcideMainWindow.getInstance().getStatusBar().setStatusMessage(filePath);

      // Builds the project file from the explorer tree node
      DefaultMutableTreeNode currentNode =
          (DefaultMutableTreeNode) currentSelection.getLastPathComponent();

      // Gets the project file from the selected node in the explorer tree
      AcideProjectFile currentProjectFile = (AcideProjectFile) currentNode.getUserObject();

      // Selects the file editor
      for (int index = 0;
          index
              < AcideMainWindow.getInstance().getFileEditorManager().getNumberOfFileEditorPanels();
          index++) {

        // If it is the file editor panel
        if (AcideMainWindow.getInstance()
            .getFileEditorManager()
            .getFileEditorPanelAt(index)
            .getAbsolutePath()
            .equals(currentProjectFile.getAbsolutePath())) {

          // Sets the selected file editor panel on it
          AcideMainWindow.getInstance().getFileEditorManager().setSelectedFileEditorPanelAt(index);
        }
      }
    }
  }
  public static void action(ActionEvent actionEvent) {
    // updates the shape of the arrow
    AcideGraphCanvas.getInstance().setArrowShape(AcideGraphCanvas.ARROW_LINE);
    AcideGraphCanvas.getInstance().repaint();
    // updates the selected component

    ((JCheckBoxMenuItem) actionEvent.getSource()).setSelected(true);
    AcideMainWindow.getInstance()
        .getMenu()
        .getConfigurationMenu()
        .getGraphPanelMenu()
        .get_arrowShapeMenu()
        .get_arrowShapePolygonMenuItem()
        .setSelected(false);
  }
  public synchronized LinkedList<String> executeCommandfinal(String commandParam) {

    LinkedList<String> res = new LinkedList<String>();

    AcideConsolePanel panel = AcideMainWindow.getInstance().getConsolePanel();

    panel.getProcessThread().getOutputGobbler().set_sendToConsole(false);

    panel.sendCommandToConsole(commandParam, "");

    boolean received = panel.getProcessThread().getOutputGobbler().waitForOKResult(2200);

    if (received) {

      String[] lines = panel.getProcessThread().getOutputGobbler().getText().split("\n");

      for (int i = 0; i < lines.length; i++) {

        // dates to catch for ddbb
        if (!lines[i].startsWith("*")
            && !lines[i].equalsIgnoreCase("$eot")
            // && !lines[i].startsWith("DES>")
            && !lines[i].startsWith(">")
            && !lines[i].startsWith("DES")
            && !lines[i].startsWith("HR")
            // && !lines[i].startsWith("DES:$des>")
            && !lines[i].startsWith("?-")
            // && !lines[i].equals("$error")
            && !lines[i].equals("$success")
            && !lines[i].contains("already in use.")
            && !lines[i].endsWith("$eot")) {

          if (!lines[i].matches("")) {

            String line = lines[i];

            res.add(line);
          }
        }
      }
    }

    panel.getProcessThread().getOutputGobbler().set_text("KO");

    panel.getProcessThread().getOutputGobbler().set_sendToConsole(true);

    return res;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  @Override
  public void actionPerformed(ActionEvent actionEvent) {

    // Performs the add opened files menu item action in the project menu
    AcideMainWindow.getInstance().getMenu().getProjectMenu().getAddOpenedFilesMenuItem().doClick();
  }
  /**
   * Searches the wanted string in the text a string.
   *
   * @param currentCaretPosition current caret position.
   * @param wantedString wanted string.
   * @param text text in which the wanted string is searched for.
   * @param isCaseSensitive is case sensitive flag.
   * @param isRegularExpresion is regular expression flag.
   * @param isCompleted is completed flag.
   * @param direction search direction.
   * @return the position of the found coincidence.
   */
  public int search(
      int currentCaretPosition,
      String wantedString,
      String text,
      boolean isCaseSensitive,
      boolean isRegularExpresion,
      boolean isCompleted,
      AcideSearchDirection direction) {

    // If regular expressions are selected
    if (isRegularExpresion) {
      try {
        // If it is not case sensitive
        if (!isCaseSensitive)

          // Compiles the pattern with case insensitive
          _pattern = Pattern.compile(wantedString, Pattern.CASE_INSENSITIVE);
        else

          // Compile the pattern with case sensitive
          _pattern = Pattern.compile(wantedString);

        // Gets the matcher
        _matcher = _pattern.matcher(text);
        _regularExpresion = " ";
      } catch (PatternSyntaxException e) {
        // Updates the log
        AcideLog.getLog().info(AcideLanguageManager.getInstance().getLabels().getString("s2148"));

        AcideSearchWindow.getInstance().setOnTop(false);

        // Displays a message
        JOptionPane.showMessageDialog(
            null, AcideLanguageManager.getInstance().getLabels().getString("s2148"));

        AcideSearchWindow.getInstance().setOnTop(true);

        // Updates the status message in the status bar in the ACIDE
        // - A Configurable IDE main window
        AcideMainWindow.getInstance()
            .getStatusBar()
            .setStatusMessage(AcideLanguageManager.getInstance().getLabels().getString("s2148"));
        return -2;
      }
      switch (direction) {
        case FORWARD:
        case BOTH:
          if (_matcher.find(currentCaretPosition)) {
            _regularExpresion = " ";
            _regularExpresion = _matcher.group(0).toString();
          }
          break;
        case BACKWARD:
        case BOTHBACK:
          int index = 0;
          int limit = currentCaretPosition;
          boolean end = false;
          _regularExpresionList.clear();

          while ((_matcher.find()) && (!end)) {
            _regularExpresionList.add(_matcher.group(0).toString());
            index =
                text.indexOf(_matcher.group(0).toString(), index)
                    + _matcher.group(0).toString().length();

            if (index > limit) {
              end = true;
              _regularExpresionList.remove(_regularExpresionList.size() - 1);
            }
          }

          break;
      }
    }

    switch (direction) {
      case FORWARD:
        return forwardSearch(
            currentCaretPosition,
            wantedString,
            text,
            isCaseSensitive,
            isRegularExpresion,
            isCompleted,
            direction);

      case BACKWARD:
        return backwardSearch(
            currentCaretPosition,
            wantedString,
            text,
            isCaseSensitive,
            isRegularExpresion,
            isCompleted,
            direction);

      case BOTH:
        return bothSearch(
            currentCaretPosition,
            wantedString,
            text,
            isCaseSensitive,
            isRegularExpresion,
            isCompleted,
            direction);

      case BOTHBACK:
        return bothBackSearch(
            currentCaretPosition,
            wantedString,
            text,
            isCaseSensitive,
            isRegularExpresion,
            isCompleted,
            direction);
    }

    return -1;
  }
  public static void action(ActionEvent actionEvent) {
    // Are you sure?
    int returnValue =
        JOptionPane.showConfirmDialog(
            null, AcideLanguageManager.getInstance().getLabels().getString("s951"));

    // If yes
    if (returnValue == JOptionPane.OK_OPTION) {

      // Gets the selection in the explorer tree
      TreePath currentSelection =
          AcideMainWindow.getInstance().getExplorerPanel().getTree().getSelectionPath();

      // If there is something selected
      if (currentSelection != null) {

        // Gets the selected node in the explorer tree
        DefaultMutableTreeNode currentNode =
            (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());

        // Transforms it into a project file
        AcideProjectFile currentProjectFile = (AcideProjectFile) currentNode.getUserObject();

        // If it is a file
        if (!currentProjectFile.isDirectory()) {

          // Gets the parent
          MutableTreeNode parentNode = (MutableTreeNode) (currentNode.getParent());

          // If it has parent
          if (parentNode != null) {

            // Removes it the node from its parent
            AcideMainWindow.getInstance()
                .getExplorerPanel()
                .getTreeModel()
                .removeNodeFromParent(currentNode);

            // Searches for the file into the project configuration
            int fileIndex = -1;
            for (int index = 0;
                index < AcideProjectConfiguration.getInstance().getNumberOfFilesFromList();
                index++) {

              if (AcideProjectConfiguration.getInstance()
                  .getFileAt(index)
                  .getAbsolutePath()
                  .equals(currentProjectFile.getAbsolutePath())) {

                // Found it
                fileIndex = index;
              }
            }

            // Gets the file from the project configuration file
            // list
            AcideProjectFile configurationFile =
                AcideProjectConfiguration.getInstance().getFileAt(fileIndex);

            // Gets its absolute path
            String absolutePath = configurationFile.getAbsolutePath();

            // Removes the file from the project configuration
            AcideProjectConfiguration.getInstance().removeFileAt(fileIndex);

            // Deletes this file
            File physicalFile = new File(absolutePath);
            physicalFile.delete();

            // Updates the status message in the status bar
            AcideMainWindow.getInstance().getStatusBar().setStatusMessage(" ");

            // The project has been modified
            AcideProjectConfiguration.getInstance().setIsModified(true);

            return;
          }
        }
      }

      // If there are more files in the project
      if (AcideProjectConfiguration.getInstance().getNumberOfFilesFromList() > 0) {

        // Updates the selected file editor index
        AcideMainWindow.getInstance()
            .getFileEditorManager()
            .updateRelatedComponentsAt(
                AcideMainWindow.getInstance()
                    .getFileEditorManager()
                    .getSelectedFileEditorPanelIndex());

        // Enables the remove file menu item in the explorer panel popup
        // menu
        AcideMainWindow.getInstance()
            .getExplorerPanel()
            .getPopupMenu()
            .getRemoveFileMenuItem()
            .setEnabled(true);

        // Enables the delete file menu item in the explorer panel popup
        // menu
        AcideMainWindow.getInstance()
            .getExplorerPanel()
            .getPopupMenu()
            .getDeleteFileMenuItem()
            .setEnabled(true);
      } else {

        // Disables the remove file menu item in the explorer panel
        // popup menu
        AcideMainWindow.getInstance()
            .getExplorerPanel()
            .getPopupMenu()
            .getRemoveFileMenuItem()
            .setEnabled(false);

        // Disables the delete file menu item in the explorer panel
        // popup menu
        AcideMainWindow.getInstance()
            .getExplorerPanel()
            .getPopupMenu()
            .getDeleteFileMenuItem()
            .setEnabled(false);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Runnable#run()
   */
  @Override
  public void run() {
    InputStream in = new ByteArrayInputStream(_input.getBytes());
    if (!AcideProjectConfiguration.getInstance().isDebugPanelShowed()) {
      AcideMainWindow.getInstance().getDebugPanel().showDebugPanel();
      AcideProjectConfiguration.getInstance().setIsDebugPanelShowed(true);
      // Updates the show debug panel check box menu item state
      AcideMainWindow.getInstance()
          .getMenu()
          .getViewMenu()
          .getShowDebugPanelCheckBoxMenuItem()
          .setSelected(AcideProjectConfiguration.getInstance().isDebugPanelShowed());

      // If it is not the default project
      if (!AcideProjectConfiguration.getInstance().isDefaultProject())

        // The project has been modified
        AcideProjectConfiguration.getInstance().setIsModified(true);
    }
    // // parses the result and generates the graph
    if (_method.equals(PARSE_TAPI_PDG)) {
      if (_destiny.equals(DESTINY_PATH))
        try {
          // parses the input to obtain the graph
          ArrayList<Node> g = AcideDebugCanvas.parsePathGraphTapi(in);
          // sets the path graph
          _canvas.setPathGraph(g);
          // updates the success flag
          _success = true;
        } catch (AcideDebugCanvasParseInputEqualsErrorException e) {
          // sets empty graphs on the path and the main graph of the canvas
          _canvas.set_graph(new DirectedWeightedGraph());
          _canvas.setPathGraph(new ArrayList<Node>());
          _canvas.repaint();
          if (_showErrorMessage) {
            // shows the error message
            new AcideDebugPanelErrorMessageDialog(
                AcideLanguageManager.getInstance().getLabels().getString("s157"), e.getMessage());
          }
          // updates the succes flag
          _success = false;
        }
      if (_destiny.equals(DESTINY_MAIN)) {
        // parses the input to obtain the graph
        _canvas.set_graph(AcideDebugCanvas.parseGraphTapi(in));
        // sets the main graph
        _success = true;
      }
    }
    // // parses the result and generates the graph
    if (_method.equals(PARSE_TAPI_RDG)) {
      if (_destiny.equals(DESTINY_PATH))
        try {
          // parses the input to obtain the graph
          ArrayList<Node> g = AcideDebugCanvas.parsePathGraphTapi(in);
          // sets the path graph
          _canvas.setPathGraph(g);
          // updates the success flag
          _success = true;
        } catch (AcideDebugCanvasParseInputEqualsErrorException e) {
          // sets empty graphs on the path and the main graph of the canvas
          _canvas.set_graph(new DirectedWeightedGraph());
          _canvas.setPathGraph(new ArrayList<Node>());
          _canvas.repaint();
          if (_showErrorMessage) {
            // shows the error message
            new AcideDebugPanelErrorMessageDialog(
                AcideLanguageManager.getInstance().getLabels().getString("s157"), e.getMessage());
          }
          // updates the succes flag
          _success = false;
        }
      if (_destiny.equals(DESTINY_MAIN)) {
        // parses the input to obtain the graph
        _canvas.set_graph(AcideDebugCanvas.parseGraphTapi(in));
        // sets the main graph
        _success = true;
      }
    }
    _canvas.repaint();
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
   * )
   */
  @Override
  public void actionPerformed(ActionEvent actionEvent) {

    try {

      // Asks the the file to the user
      String absolutePath =
          AcideFileManager.getInstance()
              .askForFile(
                  AcideFileOperation.SAVE,
                  AcideFileTarget.FILES,
                  AcideFileType.FILE,
                  "./configuration/menu/",
                  new AcideFileExtensionFilterManager(
                      new String[] {"menuConfig"},
                      AcideLanguageManager.getInstance().getLabels().getString("s287")));

      if (absolutePath != null) {

        // If it does not contain the extension
        if (!absolutePath.endsWith(".menuConfig"))

          // Adds it
          absolutePath += ".menuConfig";

        // Gets the ACIDE - A Configurable IDE current menu configuration
        String currentMenuConfiguration =
            AcideResourceManager.getInstance().getProperty("currentMenuConfiguration");

        // Copies the files
        AcideByteFileManager.getInstance().copy(currentMenuConfiguration, absolutePath);

        // Updates the ACIDE - A Configurable IDE current menu
        // configuration
        AcideResourceManager.getInstance().setProperty("currentMenuConfiguration", absolutePath);

        // Disables the save menu item
        AcideMainWindow.getInstance()
            .getMenu()
            .getConfigurationMenu()
            .getMenuMenu()
            .getSaveMenuMenuItem()
            .setEnabled(false);

        // The changes are saved
        AcideMenuConfigurationWindow.setChangesAreSaved(true);

        // Updates the log
        AcideLog.getLog()
            .info(
                AcideLanguageManager.getInstance().getLabels().getString("s528")
                    + absolutePath
                    + AcideLanguageManager.getInstance().getLabels().getString("s529"));
      }
    } catch (Exception exception) {

      // Displays an error message
      JOptionPane.showMessageDialog(
          null,
          exception.getMessage(),
          AcideLanguageManager.getInstance().getLabels().getString("s291"),
          JOptionPane.ERROR_MESSAGE);

      // Updates the log
      AcideLog.getLog().error(exception.getMessage());
    }
  }