/**
  * Validates the the paging attributes.
  *
  * @param messageList The message list.
  * @param request The request.
  */
 protected void validatePagingFields(List<MessageInfo> messageList, PagedInquiryRequest request) {
   if (ValidationUtil.isNull(request.getPageSize())
       || ValidationUtil.isNull(request.getStartPage())) {
     messageList.add(
         new MessageInfo(
             PAGING_PARAMETERS_REQUIRED,
             Message.MessageSeverity.Error,
             Message.MessageLevel.Field));
   }
 }
  /**
   * Switches validations depending on the validation context indicator.
   *
   * @param validationContext the validation context
   */
  @Override
  public void validate(ValidationContext validationContext) {
    Empresa empresa =
        (Empresa) validationContext.getObjectToBeValidated(Empresa.class.getSimpleName());

    // Do the basic check first: do I even have an Object to validate ?
    if (ValidationUtil.isNull(empresa)) {
      validationContext
          .getMessages()
          .add(
              new MessageInfo(
                  PROSPERITASGLOBAL_BASE_LOCATIONVALIDATOR_LOCATION_REQUIRED,
                  Message.MessageSeverity.Error,
                  Message.MessageLevel.Field));
      return;
    }

    // performValidation(validationContext, empresa);

    if (!validationContext.isStopProcessing()
        && !ValidationContextIndicator.FETCH_BY_ID.equals(
            validationContext.getValidationContextIndicator())) {
      validateAdditionalFields(validationContext.getMessages(), empresa);
    }
  }
  /**
   * Validate parent status.
   *
   * @param list the list
   * @param empresa the empresa
   */
  private void validateParentStatus(List<MessageInfo> list, Empresa empresa) {
    InternalResponse applyStatusResponse = new InternalResponse();
    FetchByIdRequest request = new FetchByIdRequest();

    // request.setId(empresa.getParentOrganizationId());
    // InternalResultsResponse<Organization> response =
    // getOrganizationDAC().fetchOrganizationById(request);

    // if (response.isInError())
    // {
    // applyStatusResponse.merge(response);
    // }

    // if (StatusEnum.SETUP.equals(response.getFirstResult().getStatus()))
    // {
    // list.add(
    // new MessageInfo(CBOF_BASE_APPLYSTATUS_STATUS_DENIED,
    // Message.MessageSeverity.Error,
    // Message.MessageLevel.Field,
    // new Object[] {String.valueOf(BusinessTypeEnum.LOCATION).toLowerCase(),
    // empresa.getStatus()}));
    // }

    if (!ValidationUtil.isNull(applyStatusResponse)) {
      list.addAll(applyStatusResponse.getMessageInfoList());
    }
  }
  /*
   * (non-Javadoc)
   * @see
   * com.qat.samples.sysmgmt.bac.IServicoBAC#fetchServicoById(com.qat.samples.sysmgmt.model.request.FetchByIdRequest
   * )
   */
  @Override
  public InternalResultsResponse<Servico> fetchServicoById(FetchByIdRequest request) {
    InternalResultsResponse<Servico> response = new InternalResultsResponse<Servico>();
    // validate fetchId field
    if (ValidationUtil.isNull(request.getFetchId())) {
      response.addFieldErrorMessage(SYSMGMT_BASE_ID_REQUIRED);
      response.setStatus(SystemErrorCategory.SystemValidation);
    } else {
      response.getResultsList().add(getSiteBAR().fetchServicoById(request));
    }

    return response;
  }
  /*
   * (non-Javadoc)
   * @see
   * com.prosperitasglobal.cbof.dac.ICommonBusinessObjectsDAC#updateEvento(com.prosperitasglobal.cbof.model.Evento,
   * com.qat.framework.model.response.InternalResultsResponse)
   */
  @Override
  public Integer updateEvento(Eventos endereco) {
    Integer updateCount = 0;
    InternalResultsResponse<Eventos> response = new InternalResultsResponse<Eventos>();
    // First update the root if necessary.
    if (!ValidationUtil.isNull(endereco.getModelAction())
        && (endereco.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount =
          QATMyBatisDacHelper.doUpdate(getSqlSession(), CONTACT_STMT_UPDATE, endereco, response);

      if (updateCount == 1) {
        endereco.setModelAction(QATModel.PersistanceActionEnum.NONE);
      }
    }

    return updateCount;
  }
  /*
   * (non-Javadoc)
   * @see
   * com.prosperitasglobal.cbof.dac.ICommonBusinessObjectsDAC#updateCnae(com.prosperitasglobal.cbof.model.Cnae,
   * com.qat.framework.model.response.InternalResultsResponse)
   */
  @Override
  public Integer updateCnae(Cnae cnae, InternalResultsResponse<?> response) {
    Integer updateCount = 0;
    response = new InternalResultsResponse<Cnae>();
    // First update the root if necessary.
    if (!ValidationUtil.isNull(cnae.getModelAction())
        && (cnae.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount =
          QATMyBatisDacHelper.doUpdate(getSqlSession(), CONTACT_STMT_UPDATE, cnae, response);

      if (updateCount == 1) {
        cnae.setModelAction(QATModel.PersistanceActionEnum.NONE);
      }
    }

    return updateCount;
  }
  /**
   * Validates the the sort expression is valid.
   *
   * @param messageList The message list.
   * @param request The request.
   */
  protected void validateSortFields(List<MessageInfo> messageList, PagedInquiryRequest request) {
    /*
     * If sort fields are available, then we must edit them to make sure they are valid. If none, it means
     * sorting isn't performed.
     */
    if (!ValidationUtil.isNull(getInquiryValidSortFields())) {
      List<SortExpression> badSortExpressions =
          ValidationUtil.validateSortFields(
              request.getSortExpressions(), getInquiryValidSortFields());

      if (badSortExpressions.size() > 0) {
        for (SortExpression badExpression : badSortExpressions) {
          messageList.add(
              MessageInfo.createFieldValidationError(INVALID_SORT_FIELD, badExpression.getField()));
        }
      }
    }
  }
  @Override
  public Integer updateExamePessoa(ExamePessoa banco, InternalResultsResponse<?> response) {
    Integer updateCount = 0;
    response = new InternalResultsResponse<ExamePessoa>();

    // First update the root if necessary.
    if (!ValidationUtil.isNull(banco.getModelAction())
        && (banco.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount =
          QATMyBatisDacHelper.doUpdate(
              getSqlSession(), "ExameMap.updateExamePessoa", banco, response);
    }

    if (response.isInError()) {
      return null;
    }

    return updateCount;
  }
  /*
   * (non-Javadoc)
   * @see com.qat.framework.validation.IValidator#validate(com.qat.framework.validation.ValidationContext)
   */
  @Override
  public void validate(ValidationContext context) {
    PagedInquiryRequest pagedInquiryRequest =
        (PagedInquiryRequest)
            context.getObjectToBeValidated(PagedInquiryRequest.class.getSimpleName());

    // Do the basic check first: do I even have an Object to validate ?
    if (ValidationUtil.isNull(pagedInquiryRequest)) {
      context
          .getMessages()
          .add(
              new MessageInfo(
                  PAGED_INQUIRY_REQUEST_REQUIRED,
                  Message.MessageSeverity.Error,
                  Message.MessageLevel.Field));
      return;
    }

    performValidation(context, pagedInquiryRequest);
  }
  /*
   * (non-Javadoc)
   * @see
   * com.prosperitasglobal.sendsolv.dac.IExameDAC#updateExame(com.prosperitasglobal.sendsolv.model
   * .Exame)
   */
  @Override
  public Integer updateExame(Exame banco, InternalResultsResponse<?> response) {
    Integer updateCount = 0;
    response = new InternalResultsResponse<Exame>();

    // First update the root if necessary.
    if (!ValidationUtil.isNull(banco.getModelAction())
        && (banco.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount =
          QATMyBatisDacHelper.doUpdate(getSqlSession(), EMPRESA_STMT_UPDATE, banco, response);
    }

    if (response.isInError()) {
      return null;
    }

    // Finally, if something was updated then add the Person to the result.
    // if (updateCount > 0)
    // {
    // response.addResult(banco);
    // }

    return updateCount;
  }
  @Override
  public Integer updateEventoPessoa(EventoPessoa evento) {
    Integer updateCount = 0;
    InternalResultsResponse<EventoPessoa> response = new InternalResultsResponse<EventoPessoa>();

    // First update the root if necessary.
    if (!ValidationUtil.isNull(evento.getModelAction())
        && (evento.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount =
          QATMyBatisDacHelper.doUpdate(
              getSqlSession(), "EventoMap.updateEventoPessoa", evento, response);
    }

    if (response.isInError()) {
      return null;
    }

    // Finally, if something was updated then add the Person to the result.
    if (updateCount > 0) {
      response.addResult(evento);
    }

    return updateCount;
  }
  /*
   * (non-Javadoc)
   * @see
   * com.prosperitasglobal.sendsolv.dac.ITelaDAC#updateTela(com.prosperitasglobal.sendsolv.model
   * .Tela)
   */
  @Override
  public InternalResultsResponse<Tela> updateTela(Tela tela) {
    Integer updateCount = 0;
    InternalResultsResponse<Tela> response = new InternalResultsResponse<Tela>();

    // First update the root if necessary.
    if (!ValidationUtil.isNull(tela.getModelAction())
        && (tela.getModelAction() == QATModel.PersistanceActionEnum.UPDATE)) {
      updateCount = QATMyBatisDacHelper.doUpdate(getSqlSession(), TELA_STMT_UPDATE, tela, response);
    }

    if (response.isInError()) {
      return response;
    }
    // Next traverse the object graph and "maintain" the associations
    updateCount += maintainTelaAssociations(tela, response);

    // Finally, if something was updated then add the Person to the result.
    if (updateCount > 0) {
      response.addResult(tela);
    }

    return response;
  }
  /**
   * Fetch objects by request.
   *
   * @param sqlSession the sql session
   * @param request the request
   * @param countStatement the count statement
   * @param fetchPagedStatement the fetch paged statement
   * @param response the response
   */
  @SuppressWarnings("unchecked")
  public static Integer maintainCnaeAssociations(
      List<Cnae> cnaeList,
      InternalResultsResponse<?> response,
      Integer parentId,
      TypeEnum type,
      AcaoEnum acaoType,
      TabelaEnum tabelaEnum,
      ICnaeDAC cnaeDAC,
      IStatusDAC statusDAC,
      IHistoricoDAC historicoDAC,
      Integer empId,
      String UserId,
      Integer processId) {
    Integer count = 0;
    // First Maintain Empresa
    if (ValidationUtil.isNullOrEmpty(cnaeList)) {
      return count;
    }
    // For Each Contact...
    for (Cnae cnae : cnaeList) {
      // Make sure we set the parent key
      cnae.setParentId(parentId);

      if (ValidationUtil.isNull(cnae.getModelAction())) {
        continue;
      }
      switch (cnae.getModelAction()) {
        case INSERT:
          // count = cnaeDAC.insertCnae(cnae,
          // "insertCnae", response);
          if (count > 0) {
            Status status = new Status();
            status.setStatus(CdStatusTypeEnum.ATIVO);
            List<Status> statusList = new ArrayList<Status>();
            count =
                StatusDACD.maintainStatusAssociations(
                    statusList,
                    response,
                    count,
                    null,
                    AcaoEnum.INSERT,
                    UserId,
                    empId,
                    TabelaEnum.CNAE,
                    statusDAC,
                    historicoDAC,
                    processId,
                    null);
          }
          break;
        case UPDATE:
          // count = cnaeDAC.updateCnae(cnae, response);
          if (count > 0) {
            count =
                StatusDACD.maintainStatusAssociations(
                    cnae.getStatusList(),
                    response,
                    cnae.getId(),
                    null,
                    AcaoEnum.UPDATE,
                    UserId,
                    empId,
                    TabelaEnum.CNAE,
                    statusDAC,
                    historicoDAC,
                    processId,
                    null);
          }
          break;
        case DELETE:
          Status status = new Status();
          status.setStatus(CdStatusTypeEnum.DELETADO);
          List<Status> statusList = new ArrayList<Status>();
          count =
              StatusDACD.maintainStatusAssociations(
                  statusList,
                  response,
                  cnae.getId(),
                  null,
                  AcaoEnum.DELETE,
                  UserId,
                  empId,
                  TabelaEnum.CNAE,
                  statusDAC,
                  historicoDAC,
                  processId,
                  null);

          break;
      }
    }

    return count;
  }
  /**
   * Fetch objects by request.
   *
   * @param sqlSession the sql session
   * @param request the request
   * @param countStatement the count statement
   * @param fetchPagedStatement the fetch paged statement
   * @param response the response
   */
  @SuppressWarnings("unchecked")
  public static Integer maintainConfigGeralAssociations(
      ConfigGeral configgeral,
      InternalResponse response,
      Integer parentId,
      TypeEnum type,
      AcaoEnum acaoType,
      TabelaEnum tabelaEnum,
      IConfiguracaoBAR configgeralDAC,
      IStatusBAR statusDAC,
      IHistoricoBAR historicoDAC,
      Integer empId,
      String UserId,
      Integer processId,
      Integer historicoId) {
    Boolean count = false;
    // First Maintain Empresa
    if (ValidationUtil.isNull(configgeral)) {
      return 0;
    }

    // Make sure we set the parent key
    configgeral.setParentId(parentId);
    configgeral.setTabelaEnum(tabelaEnum);
    configgeral.setProcessId(processId);

    switch (configgeral.getModelAction()) {
      case INSERT:
        count = configgeralDAC.insertConfigGeral(configgeral).hasSystemError();
        if (count == true) {
          Status status = new Status();
          status.setStatus(CdStatusTypeEnum.ATIVO);
          List<Status> statusList = new ArrayList<Status>();
          statusList.add(status);
          count =
              StatusBARD.maintainStatusAssociations(
                  statusList,
                  response,
                  parentId,
                  null,
                  AcaoEnum.INSERT,
                  UserId,
                  empId,
                  TabelaEnum.CONFIGGERAL,
                  statusDAC,
                  historicoDAC,
                  processId,
                  historicoId);
        }
        break;
      case UPDATE:
        count = configgeralDAC.updateConfigGeral(configgeral).hasSystemError();
        if (count == true) {
          count =
              StatusBARD.maintainStatusAssociations(
                  configgeral.getStatusList(),
                  response,
                  configgeral.getId(),
                  null,
                  AcaoEnum.UPDATE,
                  UserId,
                  empId,
                  TabelaEnum.CONFIGGERAL,
                  statusDAC,
                  historicoDAC,
                  processId,
                  historicoId);
        }
        break;
      case DELETE:
        count = configgeralDAC.deleteConfigGeralById(configgeral).hasSystemError();
        Status status = new Status();
        status.setStatus(CdStatusTypeEnum.DELETADO);
        List<Status> statusList = new ArrayList<Status>();
        statusList.add(status);
        count =
            StatusBARD.maintainStatusAssociations(
                statusList,
                response,
                configgeral.getId(),
                null,
                AcaoEnum.DELETE,
                UserId,
                empId,
                TabelaEnum.CONFIGGERAL,
                statusDAC,
                historicoDAC,
                processId,
                historicoId);

        break;
    }

    if (count == true) {
      return 1;
    } else {
      return 0;
    }
  }
  /**
   * Fetch objects by request.
   *
   * @param sqlSession the sql session
   * @param request the request
   * @param countStatement the count statement
   * @param fetchPagedStatement the fetch paged statement
   * @param response the response
   */
  @SuppressWarnings("unchecked")
  public static Integer maintainConecimentoTransporteAssociations(
      ConhecimentoTransporte conhecimentoTransporte,
      InternalResultsResponse<?> response,
      Integer parentId,
      TypeEnum type,
      AcaoEnum acaoType,
      TabelaEnum tabelaEnum,
      IConhecimentoTransporteDAC conecimentoTransporteDAC,
      IStatusDAC statusDAC,
      IHistoricoDAC historicoDAC,
      Integer empId,
      String UserId,
      Integer processId,
      Integer historicoId) {
    Integer count = 0;
    // First Maintain Empresa
    if (ValidationUtil.isNull(conhecimentoTransporte)) {
      return count;
    } else {
      // Make sure we set the parent key
      conhecimentoTransporte.setParentId(parentId);
      conhecimentoTransporte.setProcessId(processId);
      conhecimentoTransporte.setIdNota(parentId);

      switch (conhecimentoTransporte.getModelAction()) {
        case INSERT:
          count =
              conecimentoTransporteDAC.insertConhecimentoTransporte(
                  conhecimentoTransporte, "insertConhecimentoTransporte", response);
          if (count > 0) {
            Status status = new Status();
            status.setStatus(CdStatusTypeEnum.ATIVO);
            List<Status> statusList = new ArrayList<Status>();
            count =
                StatusDACD.maintainStatusAssociations(
                    statusList,
                    response,
                    count,
                    null,
                    AcaoEnum.INSERT,
                    UserId,
                    empId,
                    TabelaEnum.PROFISSAO,
                    statusDAC,
                    historicoDAC,
                    processId,
                    historicoId);
          }
          break;
        case UPDATE:
          count =
              conecimentoTransporteDAC.updateConhecimentoTransporte(
                  conhecimentoTransporte, response);
          if (count > 0) {
            count =
                StatusDACD.maintainStatusAssociations(
                    conhecimentoTransporte.getStatusList(),
                    response,
                    conhecimentoTransporte.getId(),
                    null,
                    AcaoEnum.UPDATE,
                    UserId,
                    empId,
                    TabelaEnum.PROFISSAO,
                    statusDAC,
                    historicoDAC,
                    processId,
                    historicoId);
          }
          break;
        case DELETE:
          Status status = new Status();
          status.setStatus(CdStatusTypeEnum.DELETADO);
          List<Status> statusList = new ArrayList<Status>();
          count =
              StatusDACD.maintainStatusAssociations(
                  statusList,
                  response,
                  conhecimentoTransporte.getId(),
                  null,
                  AcaoEnum.DELETE,
                  UserId,
                  empId,
                  TabelaEnum.PROFISSAO,
                  statusDAC,
                  historicoDAC,
                  processId,
                  historicoId);

          break;
      }
    }

    return count;
  }