/** @see org.openmrs.api.EncounterService#unvoidEncounter(org.openmrs.Encounter) */
  public Encounter unvoidEncounter(Encounter encounter) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.unvoid",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    String voidReason = encounter.getVoidReason();
    if (voidReason == null) {
      voidReason = "";
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(true)) {
      if (voidReason.equals(o.getVoidReason())) {
        os.unvoidObs(o);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (voidReason.equals(o.getVoidReason())) {
        orderService.unvoidOrder(o);
      }
    }

    encounter.setVoided(false);
    encounter.setVoidedBy(null);
    encounter.setDateVoided(null);
    encounter.setVoidReason(null);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }
  /**
   * @see org.openmrs.api.EncounterService#voidEncounter(org.openmrs.Encounter, java.lang.String)
   */
  public Encounter voidEncounter(Encounter encounter, String reason) {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          String.format(
              "Privilege %s required to void encounters of this type",
              encounter.getEncounterType().getEditPrivilege()));
    }

    if (reason == null) {
      throw new IllegalArgumentException("The argument 'reason' is required and so cannot be null");
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(false)) {
      if (!o.isVoided()) {
        os.voidObs(o, reason);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (!o.isVoided()) {
        orderService.voidOrder(o, reason);
      }
    }

    encounter.setVoided(true);
    encounter.setVoidedBy(Context.getAuthenticatedUser());
    // we expect the dateVoided to be already set by AOP logic at this point unless this method was
    // called within the API,
    // this ensures that original ParentVoidedDate and the dateVoided of associated objects will
    // always match for the
    // unvoid handler to work
    if (encounter.getDateVoided() == null) {
      encounter.setDateVoided(new Date());
    }
    encounter.setVoidReason(reason);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }