/**
   * Form to manage (add or edit) a KPI color rule.
   *
   * @param kpiDefinitionId the KPI definition id
   * @param kpiColorRuleId the KPI color rule id, set 0 for the add case
   */
  public Result manageRule(Long kpiDefinitionId, Long kpiColorRuleId) {

    // get the KPI
    KpiDefinition kpiDefinition = KpiDefinition.getById(kpiDefinitionId);
    Kpi kpi = new Kpi(kpiDefinition, getKpiService());

    // initiate the form with the template
    Form<KpiColorRuleFormData> form = kpiColorRuleFormTemplate;

    // edit case: inject values
    if (!kpiColorRuleId.equals(Long.valueOf(0))) {

      // get the KPI color rule
      KpiColorRule kpiColorRule = KpiColorRule.getById(kpiColorRuleId);

      form =
          kpiColorRuleFormTemplate.fill(
              new KpiColorRuleFormData(kpiColorRule, getI18nMessagesPlugin()));
    }

    return ok(
        views.html.admin.kpi.manageRule.render(
            kpiDefinition,
            kpi,
            form,
            Color.getColorsAsValueHolderCollection(getI18nMessagesPlugin())));
  }
  /** 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));
  }