private void checkPage(String page, CommandSender sender) {
    requestList.clear();
    requestList.addAll(plugin.requestMap.entrySet());

    int pageNumber = Integer.parseInt(page);
    if (pageNumber < 0) pageNumber = 0;
    int a = pageNumber * plugin.requestsPerPage;
    sender.sendMessage(
        ChatColor.AQUA
            + "--------- "
            + plugin.requestMap.size()
            + " Requests -"
            + ChatColor.YELLOW
            + " Open "
            + ChatColor.AQUA
            + "---------");
    if (plugin.requestMap.size() == 0) sender.sendMessage(Message.parse("checkNoRequests"));
    for (int i = (pageNumber * plugin.requestsPerPage) - plugin.requestsPerPage;
        i < a && i < requestList.size();
        i++) {
      HelpRequest currentRequest = requestList.get(i).getValue();
      if (plugin.hideWhenOffline && !RTSFunctions.isUserOnline(currentRequest.getName())) {
        a++;
        continue;
      }
      substring = RTSFunctions.shortenMessage(currentRequest.getMessage());
      date = sdf.format(new java.util.Date(currentRequest.getTimestamp() * 1000));
      ChatColor online =
          (RTSFunctions.isUserOnline(currentRequest.getName())) ? ChatColor.GREEN : ChatColor.RED;
      substring =
          (currentRequest.getStatus() == 1)
              ? ChatColor.LIGHT_PURPLE + "Claimed by " + currentRequest.getModName()
              : ChatColor.GRAY + substring;
      String bungeeServer =
          (currentRequest.getBungeeCordServer().equals(BungeeCord.getServer())
              ? ""
              : "["
                  + ChatColor.GREEN
                  + currentRequest.getBungeeCordServer()
                  + ChatColor.RESET
                  + "] ");
      sender.sendMessage(
          bungeeServer
              + ChatColor.GOLD
              + "#"
              + currentRequest.getId()
              + " "
              + date
              + " by "
              + online
              + currentRequest.getName()
              + ChatColor.GOLD
              + " - "
              + substring);
    }
  }
  private void checkSelf(CommandSender sender) {
    int openRequests = 0;
    for (Map.Entry<Integer, HelpRequest> entry : plugin.requestMap.entrySet()) {
      if (entry.getValue().getName().equals(sender.getName())) openRequests++;
    }
    int i = 0;
    sender.sendMessage(
        ChatColor.AQUA
            + "--------- "
            + ChatColor.YELLOW
            + " You have "
            + openRequests
            + " open requests "
            + ChatColor.AQUA
            + "----------");
    if (openRequests == 0)
      sender.sendMessage(ChatColor.GOLD + "You have no open requests at this time.");
    for (Map.Entry<Integer, HelpRequest> entry : plugin.requestMap.entrySet()) {
      if (entry.getValue().getName().equals(sender.getName())) {
        i++;
        if (i > 5) break;

        HelpRequest currentRequest = entry.getValue();
        substring = RTSFunctions.shortenMessage(currentRequest.getMessage());
        date = sdf.format(new java.util.Date(currentRequest.getTimestamp() * 1000));
        ChatColor online =
            (RTSFunctions.isUserOnline(currentRequest.getName())) ? ChatColor.GREEN : ChatColor.RED;
        substring =
            (currentRequest.getStatus() == 1)
                ? ChatColor.LIGHT_PURPLE + "Claimed by " + currentRequest.getModName()
                : ChatColor.GRAY + substring;
        String bungeeServer =
            (currentRequest.getBungeeCordServer().equals(BungeeCord.getServer())
                ? ""
                : "["
                    + ChatColor.GREEN
                    + currentRequest.getBungeeCordServer()
                    + ChatColor.RESET
                    + "] ");
        sender.sendMessage(
            bungeeServer
                + ChatColor.GOLD
                + "#"
                + currentRequest.getId()
                + " "
                + date
                + " by "
                + online
                + currentRequest.getName()
                + ChatColor.GOLD
                + " - "
                + substring);
      }
    }
  }
  private void checkClosed(String page, CommandSender sender) {
    int pageNumber = Integer.parseInt(page);
    int i = (pageNumber * plugin.requestsPerPage) - plugin.requestsPerPage;

    ResultSet rs = dbManager.getClosedRequests(i, plugin.requestsPerPage);
    try {
      int closedRequests = dbManager.countRequests(3);
      sender.sendMessage(
          ChatColor.AQUA
              + "--------- "
              + closedRequests
              + " Requests -"
              + ChatColor.YELLOW
              + " Closed "
              + ChatColor.AQUA
              + "--------- ");
      if (closedRequests == 0) sender.sendMessage(Message.parse("closedNoRequests"));
      while (rs.next()) {
        substring = RTSFunctions.shortenMessage(rs.getString("text"));
        date = sdf.format(new java.util.Date(rs.getLong("tstamp") * 1000));
        ChatColor online =
            (RTSFunctions.isUserOnline(rs.getString("name"))) ? ChatColor.GREEN : ChatColor.RED;
        String bServer = rs.getString("bc_server");
        String bungeeServer =
            (bServer.equals(BungeeCord.getServer())
                ? ""
                : "[" + ChatColor.GREEN + bServer + ChatColor.RESET + "] ");
        sender.sendMessage(
            bungeeServer
                + ChatColor.GOLD
                + "#"
                + rs.getInt(1)
                + " "
                + date
                + " by "
                + online
                + rs.getString("name")
                + ChatColor.GOLD
                + " - "
                + ChatColor.GRAY
                + substring);
      }
      rs.close();
    } catch (SQLException e) {
      sender.sendMessage(
          Message.parse(
              "generalInternalError", "Cannot check closed requests, see console for errors."));
      e.printStackTrace();
    }
  }
  /**
   * Initial handling of the comment sub-command.
   *
   * @param sender player that sent the command
   * @param args arguments
   * @return true if command handled correctly
   */
  public static boolean handleCommand(CommandSender sender, String[] args) {

    if (!RTSPermissions.canComment(sender)) return true;

    if (args.length < 3) return false;

    if (!RTSFunctions.isNumber(args[1])) {
      sender.sendMessage(Message.errorTicketNaN(args[1]));
      return true;
    }

    int ticketId = Integer.parseInt(args[1]);

    // Ticket has to be open in order for us to comment on it.
    if (!plugin.tickets.containsKey(ticketId)) {
      sender.sendMessage(Message.ticketNotOpen(ticketId));
      return true;
    }

    User user =
        sender instanceof Player
            ? data.getUser(((Player) sender).getUniqueId(), 0, true)
            : data.getConsole();
    if (user.getUsername() == null) {
      sender.sendMessage(
          Message.error(
              "user.getUsername() returned NULL! Are you using plugins to modify names?"));
      return true;
    }

    if (sender instanceof Player
        && plugin.tickets.get(ticketId).getUUID() != ((Player) sender).getUniqueId()
        && !RTSPermissions.isStaff((Player) sender)) {
      sender.sendMessage(Message.errorTicketOwner());
      return true;
    }

    Ticket ticket = plugin.tickets.get(ticketId);
    TreeSet<Comment> comments = ticket.getComments();

    // Clean up arguments before combining the remaining into a comment.
    args[0] = null;
    args[1] = null;

    String comment = RTSFunctions.implode(args, " ").trim();

    String name =
        sender instanceof Player
            ? plugin.staff.contains(user.getUuid())
                ? sender.getName() + " - Staff"
                : sender.getName()
            : sender.getName();

    long timestamp = System.currentTimeMillis() / 1000;

    // Create a comment and store the comment ID.
    int commentId = data.createComment(name, timestamp, comment, ticketId);
    // If less than 1, then the creation of the comment failed.
    if (commentId < 1) {
      sender.sendMessage(Message.error("Comment could not be created."));
      return true;
    }

    sender.sendMessage(Message.ticketCommentUser(Integer.toString(ticketId)));

    // Notify staff members about the new comment.
    try {
      // Attempt to notify all servers connected to BungeeCord that run ReportRTS.
      BungeeCord.globalNotify(
          Message.ticketComment(Integer.toString(ticketId), user.getUsername()),
          ticketId,
          NotificationType.NOTIFYONLY);
    } catch (IOException e) {
      e.printStackTrace();
    }

    RTSFunctions.messageStaff(
        Message.ticketComment(Integer.toString(ticketId), user.getUsername()), true);

    // Add a comment to the comment set.
    comments.add(new Comment(timestamp, ticketId, commentId, sender.getName(), comment));
    // Update the comments on the ticket.
    ticket.setComments(comments);
    plugin.tickets.put(ticketId, ticket);

    plugin
        .getServer()
        .getPluginManager()
        .callEvent(new TicketCommentEvent(plugin.tickets.get(ticketId), sender, comment));

    return true;
  }
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    double start = 0;
    if (plugin.debugMode) start = System.nanoTime();
    if (!RTSPermissions.canCheckAllRequests(sender)) {
      if (!RTSPermissions.canCheckOwnRequests(sender)) {
        sender.sendMessage(
            Message.parse(
                "generalPermissionError",
                "reportrts.command.check or reportrts.command.check.self"));
        return true;
      }
      if (args.length > 0) {
        sender.sendMessage(
            ChatColor.RED + "You may only use /check to check the status of your requests.");
        return true;
      }
      checkSelf(sender);
      if (plugin.debugMode)
        Message.debug(
            sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
      return true;
    }
    if (args.length == 0) {
      checkPage("1", sender);
      if (plugin.debugMode)
        Message.debug(
            sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
      return true;
    }
    if (!RTSFunctions.isParsableToInt(args[0])) {
      switch (args[0].toUpperCase()) {
        case "P":
        case "PAGE":
          try {
            checkPage(args[1], sender);
          } catch (ArrayIndexOutOfBoundsException e) {
            checkPage("1", sender);
          }
          break;

        case "H":
        case "HELD":
          try {
            checkHeld(args[1], sender);
          } catch (ArrayIndexOutOfBoundsException e) {
            checkHeld("1", sender);
          }
          break;

        case "C":
        case "CLOSED":
          try {
            checkClosed(args[1], sender);
          } catch (ArrayIndexOutOfBoundsException e) {
            checkClosed("1", sender);
          }
          break;

        case "S":
        case "SERVER":
          try {
            checkServer((args.length > 1 ? args[2] : "1"), args[1], sender);
          } catch (ArrayIndexOutOfBoundsException e) {
            checkServer("1", BungeeCord.getServer(), sender);
          }
          break;

        default:
          if (plugin.debugMode)
            Message.debug(
                sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
          return false;
      }
      if (plugin.debugMode)
        Message.debug(
            sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
      return true;
    }

    checkId(Integer.parseInt(args[0]), sender);
    if (plugin.debugMode)
      Message.debug(sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
    return true;
  }
  private void checkId(int id, CommandSender sender) {
    HelpRequest currentRequest = plugin.requestMap.get(id);

    if (currentRequest == null) {
      ResultSet rs = dbManager.getTicketById(id);

      ChatColor online;
      try {
        if (plugin.storageType.equalsIgnoreCase("mysql")) {
          if (rs.isBeforeFirst()) rs.first();
        }
        online =
            (RTSFunctions.isUserOnline(rs.getString("name"))) ? ChatColor.GREEN : ChatColor.RED;
        date = sdf.format(new java.util.Date(rs.getLong("tstamp") * 1000));
        String status = null;
        ChatColor statusColor = null;

        if (rs.getInt("status") == 0) {
          status = "Open";
          statusColor = ChatColor.YELLOW;
        }
        if (rs.getInt("status") == 1) {
          status = "Claimed";
          statusColor = ChatColor.RED;
        }
        if (rs.getInt("status") == 2) {
          status = "On Hold";
          statusColor = ChatColor.LIGHT_PURPLE;
        }
        if (rs.getInt("status") == 3) {
          status = "Closed";
          statusColor = ChatColor.GREEN;
        }
        String text = rs.getString("text");
        String bungeeServer = rs.getString("bc_server");
        String modComment = rs.getString("mod_comment");

        sender.sendMessage(
            ChatColor.AQUA
                + "--------- "
                + "Request #"
                + rs.getInt(1)
                + " - "
                + statusColor
                + status
                + ChatColor.AQUA
                + " ---------");
        sender.sendMessage(
            ChatColor.YELLOW
                + "Filed by"
                + online
                + " "
                + rs.getString("name")
                + ChatColor.YELLOW
                + " at "
                + ChatColor.GREEN
                + date
                + ChatColor.YELLOW
                + " at X:"
                + ChatColor.GREEN
                + rs.getInt("x")
                + ChatColor.YELLOW
                + ", Y:"
                + ChatColor.GREEN
                + rs.getInt("y")
                + ChatColor.YELLOW
                + ", Z:"
                + ChatColor.GREEN
                + rs.getInt("z"));

        if (rs.getInt("status") == 3) {
          int modId = rs.getInt("mod_id");
          sender.sendMessage(
              ChatColor.LIGHT_PURPLE + "Handled by " + dbManager.getUserName(modId) + ".");
          int Millis = (rs.getInt("mod_timestamp") - rs.getInt("tstamp")) * 1000;
          sender.sendMessage(
              ChatColor.LIGHT_PURPLE
                  + String.format(
                      "Time spent: %d hours, %d minutes, %d seconds",
                      Millis / (1000 * 60 * 60),
                      (Millis % (1000 * 60 * 60)) / (1000 * 60),
                      ((Millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000));
        } else if (rs.getInt("status") > 0) {
          int modId = rs.getInt("mod_id");
          sender.sendMessage(
              ChatColor.LIGHT_PURPLE + "Claimed by " + dbManager.getUserName(modId) + ".");
        }
        if (!bungeeServer.equals(BungeeCord.getServer()))
          sender.sendMessage(
              ChatColor.YELLOW + "BungeeCord Server: " + ChatColor.GREEN + bungeeServer);
        if (modComment != null)
          sender.sendMessage(ChatColor.YELLOW + "Comment: " + ChatColor.DARK_GREEN + modComment);
        sender.sendMessage(ChatColor.GRAY + text);

        rs.close();
        return;
      } catch (SQLException e) {
        sender.sendMessage(Message.parse("generalRequestNotFound", id));
        return;
      }
    }

    ChatColor online =
        (RTSFunctions.isUserOnline(currentRequest.getName())) ? ChatColor.GREEN : ChatColor.RED;
    date = sdf.format(new java.util.Date(currentRequest.getTimestamp() * 1000));
    String status;
    if (currentRequest.getStatus() == 1) {
      status = ChatColor.RED + "Claimed";
    } else {
      status = ChatColor.YELLOW + "Open";
    }

    sender.sendMessage(
        ChatColor.AQUA
            + "--------- "
            + " Request #"
            + currentRequest.getId()
            + " -"
            + ChatColor.YELLOW
            + " "
            + status
            + " "
            + ChatColor.AQUA
            + "---------");
    sender.sendMessage(
        ChatColor.YELLOW
            + "Filed by"
            + online
            + " "
            + currentRequest.getName()
            + ChatColor.YELLOW
            + " at "
            + ChatColor.GREEN
            + date
            + ChatColor.YELLOW
            + " at X:"
            + ChatColor.GREEN
            + currentRequest.getX()
            + ChatColor.YELLOW
            + ", Y:"
            + ChatColor.GREEN
            + currentRequest.getY()
            + ChatColor.YELLOW
            + ", Z:"
            + ChatColor.GREEN
            + currentRequest.getZ());
    sender.sendMessage(ChatColor.GRAY + currentRequest.getMessage());

    if (currentRequest.getStatus() == 1) {
      long Millis = (System.currentTimeMillis() - (currentRequest.getModTimestamp()) * 1000);
      sender.sendMessage(
          ChatColor.LIGHT_PURPLE
              + String.format(
                  "Claimed for: %d hours, %d minutes, %d seconds",
                  Millis / (1000 * 60 * 60),
                  (Millis % (1000 * 60 * 60)) / (1000 * 60),
                  ((Millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000));
    }
  }
  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (args.length == 0) return false;
    if (!(sender instanceof Player)) {
      sender.sendMessage("[ReportRTS] Some information will not be correct, such as location.");
      int userId = dbManager.getUserId("CONSOLE", true);
      String message = RTSFunctions.implode(args, " ");
      Location location = plugin.getServer().getWorlds().get(0).getSpawnLocation();
      String world = plugin.getServer().getWorlds().get(0).getName();
      if (!dbManager.fileRequest("CONSOLE", world, location, message, userId)) {
        sender.sendMessage(Message.parse("generalInternalError", "Request could not be filed."));
        return true;
      }
      int ticketId = dbManager.getLatestTicketIdByUser(userId);
      HelpRequest request =
          new HelpRequest(
              "CONSOLE",
              ticketId,
              System.currentTimeMillis() / 1000,
              message,
              0,
              location.getBlockX(),
              location.getBlockY(),
              location.getBlockZ(),
              location.getYaw(),
              location.getPitch(),
              world,
              BungeeCord.getServer(),
              "");
      plugin.getServer().getPluginManager().callEvent(new ReportCreateEvent(request));
      plugin.requestMap.put(ticketId, request);
      if (plugin.notifyStaffOnNewRequest) {
        try {
          BungeeCord.globalNotify(
              Message.parse("modreqFiledMod", "CONSOLE", ticketId), ticketId, NotificationType.NEW);
        } catch (IOException e) {
          e.printStackTrace();
        }
        RTSFunctions.messageMods(Message.parse("modreqFiledMod", "CONSOLE", ticketId), true);
      }
      return true;
    }
    if (!RTSPermissions.canFileRequest(sender)) return true;
    if (plugin.requestMinimumWords > args.length) {
      sender.sendMessage(Message.parse("modreqTooShort", plugin.requestMinimumWords));
      return true;
    }
    if (RTSFunctions.getOpenRequestsByUser(sender) >= plugin.maxRequests
        && !(ReportRTS.permission != null
            ? ReportRTS.permission.has(sender, "reportrts.command.modreq.unlimited")
            : sender.hasPermission("reportrts.command.modreq.unlimited"))) {
      sender.sendMessage(Message.parse("modreqTooManyOpen"));
      return true;
    }
    if (plugin.requestDelay > 0) {
      if (!(ReportRTS.permission != null
          ? ReportRTS.permission.has(sender, "reportrts.command.modreq.unlimited")
          : sender.hasPermission("reportrts.command.modreq.unlimited"))) {
        long timeBetweenRequest = RTSFunctions.checkTimeBetweenRequests(sender);
        if (timeBetweenRequest > 0) {
          sender.sendMessage(Message.parse("modreqTooFast", timeBetweenRequest));
          return true;
        }
      }
    }
    double start = 0;
    if (plugin.debugMode) start = System.nanoTime();

    Player player = (Player) sender;
    String message = RTSFunctions.implode(args, " ");
    int userId = dbManager.getUserId(player.getName(), true);
    if (!dbManager.fileRequest(
        player.getName(), player.getWorld().getName(), player.getLocation(), message, userId)) {
      sender.sendMessage(Message.parse("generalInternalError", "Request could not be filed."));
      return true;
    }
    int ticketId = dbManager.getLatestTicketIdByUser(userId);

    Location location = player.getLocation();

    sender.sendMessage(Message.parse("modreqFiledUser"));
    plugin.getLogger().log(Level.INFO, "" + player.getName() + " filed a request.");
    if (plugin.notifyStaffOnNewRequest) {
      try {
        BungeeCord.globalNotify(
            Message.parse("modreqFiledMod", player.getName(), ticketId),
            ticketId,
            NotificationType.NEW);
      } catch (IOException e) {
        e.printStackTrace();
      }
      RTSFunctions.messageMods(Message.parse("modreqFiledMod", player.getName(), ticketId), true);
    }

    HelpRequest request =
        new HelpRequest(
            player.getName(),
            ticketId,
            System.currentTimeMillis() / 1000,
            message,
            0,
            location.getBlockX(),
            location.getBlockY(),
            location.getBlockZ(),
            location.getYaw(),
            location.getPitch(),
            player.getWorld().getName(),
            BungeeCord.getServer(),
            "");
    plugin.getServer().getPluginManager().callEvent(new ReportCreateEvent(request));
    plugin.requestMap.put(ticketId, request);
    if (plugin.debugMode)
      Message.debug(sender.getName(), this.getClass().getSimpleName(), start, cmd.getName(), args);
    return true;
  }