/**
   * Change the order of a KPI color rule comparing to the other rules of the corresponding KPI.
   *
   * @param kpiColorRuleId the KPI color rule id
   * @param isDecrement if true then we decrement the order, else we increment it
   */
  public Result changeRuleOrder(Long kpiColorRuleId, Boolean isDecrement) {

    KpiColorRule kpiColorRule = KpiColorRule.getById(kpiColorRuleId);

    KpiColorRule kpiColorRuleToReverse = null;
    if (isDecrement) {
      kpiColorRuleToReverse =
          KpiColorRule.getPrevious(kpiColorRule.kpiDefinition.id, kpiColorRule.order);
    } else {
      kpiColorRuleToReverse =
          KpiColorRule.getNext(kpiColorRule.kpiDefinition.id, kpiColorRule.order);
    }

    if (kpiColorRuleToReverse != null) {

      Integer newOrder = kpiColorRuleToReverse.order;

      kpiColorRuleToReverse.order = kpiColorRule.order;
      kpiColorRuleToReverse.save();

      kpiColorRule.order = newOrder;
      kpiColorRule.save();

      reloadKpiDefinition(kpiColorRule.kpiDefinition.uid);
    }

    return redirect(
        controllers.admin.routes.KpiManagerController.view(kpiColorRule.kpiDefinition.id));
  }
  /** Process the manage form of a KPI color rule. */
  public Result saveRule() {

    // bind the form
    Form<KpiColorRuleFormData> boundForm = kpiColorRuleFormTemplate.bindFromRequest();

    // get the KPI
    Long kpiDefinitionId = Long.valueOf(boundForm.data().get("kpiDefinitionId"));
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiDefinitionId);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    if (boundForm.hasErrors()) {
      return ok(
          views.html.admin.kpi.manageRule.render(
              kpiDefinition,
              kpi,
              boundForm,
              Color.getColorsAsValueHolderCollection(getI18nMessagesPlugin())));
    }

    KpiColorRuleFormData kpiColorRuleFormData = boundForm.get();

    KpiColorRule kpiColorRule = null;

    if (kpiColorRuleFormData.kpiColorRuleId == null) { // create case

      kpiColorRule = new KpiColorRule();

      kpiColorRule.kpiDefinition = kpiDefinition;
      kpiColorRule.order = KpiColorRule.getLastOrder(kpiDefinition.id) + 1;

      kpiColorRuleFormData.fill(kpiColorRule);

      kpiColorRule.save();

      Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.rule.add.successful"));

    } else { // edit case

      kpiColorRule = KpiColorRule.getById(kpiColorRuleFormData.kpiColorRuleId);

      kpiColorRuleFormData.fill(kpiColorRule);

      kpiColorRule.update();

      Utilities.sendSuccessFlashMessage(Msg.get("admin.kpi.rule.edit.successful"));
    }

    kpiColorRuleFormData.renderLabel.persist(getI18nMessagesPlugin());

    reloadKpiDefinition(kpiDefinition.uid);

    return redirect(controllers.admin.routes.KpiManagerController.view(kpiDefinition.id));
  }