/*
   * (non-Javadoc)
   * @see
   * com.sensus.mlc.light.bcf.ILightBCF#updateSchedule(com.sensus.mlc.light.model.request.ScheduleMaintenanceRequest)
   */
  @Override
  public ScheduleMaintenanceResponse updateSchedule(ScheduleMaintenanceRequest request) {
    ScheduleMaintenanceResponse response = new ScheduleMaintenanceResponse();

    try {
      InternalResponse internalResponse = null;

      ValidationContext context =
          new ValidationContext(
              ScheduleMaintenanceRequest.class.getSimpleName(),
              request,
              MLCPersistanceActionEnum.getSlcActionName(),
              MLCPersistanceActionEnum.UPDATE_SCHEDULE);

      if (!getRequestValidationController().validate(context)) // Validate Tenant and UserContext
      {
        handleOperationStatusAndMessages(response, internalResponse, context.getMessages(), true);
        return response;
      }

      if (ValidationUtil.isNull(request.getSchedule())
          || ValidationUtil.isNull(request.getSchedule().getParentId())) {
        response.addMessage(
            MessageInfo.createFieldValidationError(SENSUS_MLC_VALIDATOR_PARENT_ID_REQUIRED));
        return response;
      }

      internalResponse = getLightBCL().updateSchedule(request);
      handleOperationStatusAndMessages(response, internalResponse, null, true);

    } catch (Exception ex) {
      SensusInterfaceUtil.handleException(LOG, response, ex, DEFAULT_LIGHT_BCF_EXCEPTION_MSG);
    }
    return response;
  }
  /*
   * (non-Javadoc)
   * @see com.sensus.mlc.tabela.bcf.ITabelaBCF#insertTabela(com.sensus.mlc.tabela.model.request.TabelaRequest)
   */
  @Override
  public TabelaResponse insertTabela(TabelaRequest tabelaRequest) {
    TabelaResponse response = new TabelaResponse();
    InternalResultsResponse<Tabela> internalResponse = null;
    try {
      ValidationContext context = new ValidationContext();
      context.getValidationArguments().put(getSlcActionName(), INSERT);
      context.putObjectToBeValidated(TABELA_REQUEST_NAME, tabelaRequest);
      context.putObjectToBeValidated(TABELA_NAME, tabelaRequest.getTabela());

      if (getLightingControlRequestValidationController().validate(context)
          && getTabelaValidationController().validate(context)) {

        if (getLightListValidationController().validate(context)) {
          internalResponse = getTabelaBCL().insertTabela(tabelaRequest);
          response.setTabela(internalResponse.getResultsList());
        }
      }

      handleOperationStatusAndMessages(response, internalResponse, context.getMessages(), true);
    } catch (Exception ex) {
      SensusInterfaceUtil.handleException(LOG, response, ex, DEFAULT_TABELA_BCF_EXCEPTION_MSG);
    }
    return response;
  }
  /*
   * (non-Javadoc)
   * @see com.sensus.mlc.lflivrofiscal.bcf.ILflivrofiscalBCF#insertLflivrofiscal(com.sensus.mlc.lflivrofiscal.model.request.LflivrofiscalRequest)
   */
  @Override
  public LflivrofiscalResponse insertLflivrofiscal(LflivrofiscalRequest lflivrofiscalRequest) {
    LflivrofiscalResponse response = new LflivrofiscalResponse();
    InternalResultsResponse<Lflivrofiscal> internalResponse = null;
    try {
      ValidationContext context = new ValidationContext();
      context.getValidationArguments().put(getSlcActionName(), INSERT);
      context.putObjectToBeValidated(LFLIVROFISCAL_REQUEST_NAME, lflivrofiscalRequest);
      context.putObjectToBeValidated(LFLIVROFISCAL_NAME, lflivrofiscalRequest.getLflivrofiscal());

      if (getLightingControlRequestValidationController().validate(context)
          && getLflivrofiscalValidationController().validate(context)) {

        if (getLightListValidationController().validate(context)) {
          internalResponse = getLflivrofiscalBCL().insertLflivrofiscal(lflivrofiscalRequest);
          response.setLflivrofiscal(internalResponse.getResultsList());
        }
      }

      handleOperationStatusAndMessages(response, internalResponse, context.getMessages(), true);
    } catch (Exception ex) {
      SensusInterfaceUtil.handleException(
          LOG, response, ex, DEFAULT_LFLIVROFISCAL_BCF_EXCEPTION_MSG);
    }
    return response;
  }
  /**
   * Update.
   *
   * @param request the request
   * @return the response
   */
  @RequestMapping(value = UPDATE, method = RequestMethod.POST)
  @ResponseBody
  public Response update(@RequestBody Map<String, Object> request) {
    ScheduleResponse response = new ScheduleResponse();

    try {
      ScheduleRequest scheduleRequest =
          new ScheduleRequest(new DMSchedule(Integer.parseInt(request.get(ID).toString())));

      // ADD user context to request
      addUserContextToRequest(scheduleRequest);

      response = getScheduleBCF().fetchScheduleById(scheduleRequest);
      if (!response.isOperationSuccess()) {
        return response;
      }

      DMSchedule schedule = response.getSchedules().get(0);

      if (STATUS_PAUSED.equals(request.get(TYPE))) {
        schedule.setStatusEnum(ScheduleStatusEnum.PAUSED);
      } else if (STATUS_RESUME.equals(request.get(TYPE))) {
        schedule.setStatusEnum(ScheduleStatusEnum.ENABLED);
      } else if (STATUS_FAILED.equals(request.get(TYPE))) {
        schedule.setStatusEnum(ScheduleStatusEnum.ENABLED);

        // New Next Execution Date
        Date serverUTC = DMConvertUtil.convertDateToDefaultUTC(new Date());

        // New Action Date = New Next Execution Date + (Old Action Date - Old Next Execution Date)
        Date actionDate =
            DMConvertUtil.convertDateToDefaultUTC(
                DMConvertUtil.convertIntegerToDate(
                    DMConvertUtil.convertDateToInteger(serverUTC)
                        + (DMConvertUtil.convertDateToInteger(
                                DMConvertUtil.convertDateToDefaultUTC(
                                    schedule.getDmAction().getActionTime()))
                            - DMConvertUtil.convertDateToInteger(
                                DMConvertUtil.convertDateToDefaultUTC(
                                    schedule.getFrequency().getNextExecution())))));

        schedule.getDmAction().setActionTime(actionDate);
        schedule.getFrequency().setNextExecution(serverUTC);
      }

      scheduleRequest.setSchedule(schedule);

      response = getScheduleBCF().updateScheduleStatus(scheduleRequest);

    } catch (Exception e) {
      SensusInterfaceUtil.handleException(
          LOG, response, e, DEFAULT_EXCEPTION_MSG, new String[] {CONTROLLER_EXCEPTION_MSG});
    }

    return response;
  }
 @Override
 public EmpresaResponse deleteEmpresa(EmpresaRequest empresaRequest) {
   EmpresaResponse response = new EmpresaResponse();
   try {
     //			if (LCHelp.checkValidation(response, empresaRequest, MLCPersistanceActionEnum.DELETE))
     //			{
     InternalResponse internalResponse = getEmpresaBCL().deleteEmpresa(empresaRequest);
     //				LCHelp.treatReturnFromBCL(response, internalResponse,
     // DEFAULT_EMPRESA_BCF_EXCEPTION_MSG);
     //			}
   } catch (Exception ex) {
     SensusInterfaceUtil.handleException(LOG, response, ex, DEFAULT_EMPRESA_BCF_EXCEPTION_MSG);
   }
   return response;
 }
 @Override
 public EmpresaResponse fetchAllEmpresaFilial(EmpresaRequest empresaRequest) {
   EmpresaResponse response = new EmpresaResponse();
   try {
     //			if (LCHelp.checkValidation(response, inquiryEmpresaRequest,
     // MLCPersistanceActionEnum.FETCH))
     //			{
     InternalResultsResponse<Empresa> internalResponse =
         getEmpresaBCL().fetchAllEmpresaFilial(empresaRequest);
     response.setEmpresa(internalResponse.getResultsList());
     //				LCHelp.treatReturnFromBCL(response, internalResponse,
     // DEFAULT_EMPRESA_BCF_EXCEPTION_MSG);
     //			}
   } catch (Exception ex) {
     SensusInterfaceUtil.handleException(LOG, response, ex, DEFAULT_EMPRESA_BCF_EXCEPTION_MSG);
   }
   return response;
 }
  /*
   * (non-Javadoc)
   * @see com.sensus.mlc.tabela.bcf.ITabelaBCF#fetchAllTabelas(com.sensus.mlc.tabela.model.request.InquiryTabelaRequest
   */
  @Override
  public InquiryTabelaResponse fetchAllTabela(InquiryTabelaRequest inquiryTabelaRequest) {
    InquiryTabelaResponse response = new InquiryTabelaResponse();
    InternalResultsResponse<Tabela> internalResponse = null;

    try {
      ValidationContext context = new ValidationContext();
      context.putObjectToBeValidated(INQUIRY_TABELA_REQUEST_NAME, inquiryTabelaRequest);

      if (getLightingControlRequestValidationController().validate(context)) {
        internalResponse = getTabelaBCL().fetchAllTabela(inquiryTabelaRequest);
      }

      handleOperationStatusAndMessages(response, internalResponse, context.getMessages(), true);
    } catch (Exception ex) {
      SensusInterfaceUtil.handleException(LOG, response, ex, DEFAULT_TABELA_BCF_EXCEPTION_MSG);
    }

    return response;
  }
  /**
   * Delete.
   *
   * @param request the request
   * @return the response
   */
  @RequestMapping(value = DELETE, method = RequestMethod.POST)
  @ResponseBody
  public Response delete(@RequestBody Map<String, Integer> request) {
    ScheduleResponse response = new ScheduleResponse();

    try {
      ScheduleRequest scheduleRequest = new ScheduleRequest();

      // ADD user context to request
      addUserContextToRequest(scheduleRequest);

      scheduleRequest.setSchedule(new DMSchedule(request.get(ID)));

      response = getScheduleBCF().deleteSchedule(scheduleRequest);
    } catch (Exception e) {
      SensusInterfaceUtil.handleException(
          LOG, response, e, DEFAULT_EXCEPTION_MSG, new String[] {CONTROLLER_EXCEPTION_MSG});
    }

    return response;
  }
  /**
   * Fetch all.
   *
   * @param request the request
   * @return the response
   */
  @RequestMapping(value = FETCH_ALL, method = RequestMethod.POST)
  @ResponseBody
  public Response fetchAll(@RequestBody InquiryScheduleRequest request) {
    InquiryScheduleResponse inquiryScheduleResponse = new InquiryScheduleResponse();

    try {
      if (ValidationUtil.isNullOrEmpty(request.getScheduleStatusEnums())
          && request.getSortExpressions().get(0).getField().equals("action_date")) {
        request.getSortExpressions().clear();
        request
            .getSortExpressions()
            .add(new SortExpression(ScheduleOrderByEnum.STATUS.getValue(), Direction.Ascending));
        request
            .getSortExpressions()
            .add(
                new SortExpression(
                    ScheduleOrderByEnum.ACTION_DATE.getValue(), Direction.Ascending));
      }

      // ADD user context to request
      addUserContextToRequest(request);

      request.setPreQueryCount(true);

      inquiryScheduleResponse = getScheduleBCF().fetchAllSchedule(request);
    } catch (Exception e) {
      SensusInterfaceUtil.handleException(
          LOG,
          inquiryScheduleResponse,
          e,
          DEFAULT_EXCEPTION_MSG,
          new String[] {CONTROLLER_EXCEPTION_MSG});
    }

    return inquiryScheduleResponse;
  }
  /**
   * Insert.
   *
   * @param scheduleModel the schedule model
   * @return the response
   */
  @RequestMapping(value = "upload", method = RequestMethod.POST)
  public ScheduleModel upload(ScheduleModel scheduleModel, HttpServletRequest request) {
    ScheduleResponse response = new ScheduleResponse();

    ScheduleRequest scheduleRequest = new ScheduleRequest();

    try {

      addUserContextToRequest(scheduleRequest);

      if (!ValidationUtil.isNull(scheduleModel.getImportBy())) {
        if (scheduleModel.getImportBy().equals(DEVICE_ID)) {
          scheduleRequest.setIdFileType(PropertyEnum.DEVICE_ID);
        } else if (scheduleModel.getImportBy().equals(NETWORD_ADDRESS)) {
          scheduleRequest.setIdFileType(PropertyEnum.NETWORK_ADDRESS);
        }
      }

      if (!ValidationUtil.isNull(scheduleModel.getUpload())) {
        File f = new File(FILE_NAME);
        scheduleModel.getUpload().transferTo(f);
        scheduleRequest.setIdsFile(f);
      } else if (!ValidationUtil.isNullOrEmpty(scheduleModel.getMeterList())) {
        scheduleRequest.setUploadIds(scheduleModel.getMeterList());
      }

      if (!ValidationUtil.isNull(scheduleModel.getbMonitored())) {
        scheduleRequest.setIsMonitored(scheduleModel.getbMonitored());
      }

      if (ValidationUtil.isNull(scheduleModel.getScheduledEventId())) {
        scheduleRequest.setSchedule(validationInsertSchedule(INSERT, scheduleModel));
        response = getScheduleBCF().insertSchedule(scheduleRequest);

        if (response.isOperationSuccess()) {
          scheduleModel.setMessageSuccess(INSERT);
        }
      } else {
        scheduleRequest.setSchedule(validationInsertSchedule(UPDATE, scheduleModel));
        response = getScheduleBCF().updateSchedule(scheduleRequest);

        if (response.isOperationSuccess()) {
          scheduleModel.setMessageSuccess(UPDATE);
        }
      }

      if (response.isOperationSuccess()) {
        scheduleModel.setUploadFileProcess(scheduleRequest.getFileName());
        scheduleModel.setActionId(response.getSchedules().get(0).getDmAction().getId().toString());
        scheduleModel.setScheduledEventName(scheduleRequest.getSchedule().getName());
        scheduleModel.setProcessId(scheduleRequest.getProcessId());
      } else {
        for (Message msg : response.getMessageList()) {
          scheduleModel.setMessageError(msg.getText());
        }
      }
    } catch (Exception e) {
      SensusInterfaceUtil.handleException(
          LOG, response, e, DEFAULT_EXCEPTION_MSG, new String[] {CONTROLLER_EXCEPTION_MSG});
    }

    return scheduleModel;
  }
  /**
   * Fetch.
   *
   * @param request the request
   * @return the response
   */
  @SuppressWarnings("unchecked")
  @RequestMapping(value = FETCH, method = RequestMethod.POST)
  @ResponseBody
  public Response fetch(@RequestBody Map<String, Object> request) {
    ScheduleResponse response = new ScheduleResponse();
    try {
      ScheduleRequest scheduleRequest = new ScheduleRequest();

      // ADD user context to request
      addUserContextToRequest(scheduleRequest);

      // Call fetchScheduleById method for to open schedule dialog on schedule page
      if (OPEN_UPDATE_BY_ID.equals(request.get(TYPE))) {
        DMSchedule schedule = new DMSchedule(Integer.parseInt(request.get(ID).toString()));
        scheduleRequest.setSchedule(schedule);

        return getScheduleBCF().fetchScheduleById(scheduleRequest);
      }

      // Call fetchScheduleByDevice method for to load schedule list at device detail page.
      if (SCHEDULE_BY_DEVICE.equals(request.get(TYPE))) {
        DMAction action = new DMAction();

        Device device = new Device(new Radio(new BigInteger(request.get(ID).toString())));
        action.addDevice(device);

        DMSchedule epmSchedule = new DMSchedule();
        epmSchedule.setDmAction(action);
        scheduleRequest.setSchedule(epmSchedule);

        return getScheduleBCF().fetchScheduleByDevice(scheduleRequest);
      }

      // Call fetchScheduleByGroup method for to verify if the group is scheduled or no.
      if (CHECK_SCHEDULE.equals(request.get(TYPE))) {
        DMAction action = new DMAction();

        action.setGroups(new ArrayList<Group>());

        List<String> ids = (ArrayList<String>) request.get(ID);

        for (String idGroup : ids) {
          action.getGroups().add(new Group(Integer.parseInt(idGroup)));
        }

        DMSchedule epmSchedule = new DMSchedule();
        epmSchedule.setDmAction(action);
        scheduleRequest.setSchedule(epmSchedule);

        return getScheduleBCF().fetchScheduleByGroup(scheduleRequest);
      }

      // Call fetchScheduleByName for to check if the schedule name there is already.
      if (CHECK_EVENT.equals(request.get(TYPE))) {
        scheduleRequest.setSchedule(new DMSchedule(request.get(SCHEDULE_NAME).toString()));

        return getScheduleBCF().fetchScheduleByName(scheduleRequest);
      }

      // Call fetchScheduleByAction method for to open schedule dialog on other pages
      if (OPEN_UPDATE_BY_ACTION.equals(request.get(TYPE))) {
        DMSchedule epmSchedule = new DMSchedule();
        epmSchedule.setDmAction(new DMAction(Integer.parseInt(request.get(ID).toString())));
        scheduleRequest.setSchedule(epmSchedule);

        return getScheduleBCF().fetchScheduleByAction(scheduleRequest);
      }
    } catch (Exception e) {
      SensusInterfaceUtil.handleException(
          LOG, response, e, DEFAULT_EXCEPTION_MSG, new String[] {CONTROLLER_EXCEPTION_MSG});
    }
    return response;
  }