package com.dla.dda.rest;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import com.dla.dda.bussines.ContratoBussines;
import com.dla.dda.domain.constants.ErrorCodes;
import com.dla.dda.domain.contrato.ContratoDDA;
import com.dla.dda.domain.exceptions.utils.ErrorUtils;
import com.dla.dda.domain.model.request.ContratoRequest;
import com.dla.dda.domain.model.response.ContratoResponse;
import com.dla.dda.utils.transaction.TransactionState;

@Service
public class ContratoRestService implements IContratoRestService {

	private static Logger logger = LoggerFactory.getLogger(ContratoRestService.class);

	@Autowired
	private ContratoBussines service;

	@Override
	public ContratoResponse findContratosXEstudio(ContratoRequest request) {
		logger.info("findContratosXEstudio");
		logger.info("{}", request);

		TransactionState.Current().initialize();
		ErrorCodes code = ErrorCodes.SUCCESS_PROCESS;

		StopWatch watch = new StopWatch();
		watch.start();

		ContratoResponse response = new ContratoResponse();

		try {
			List<ContratoDDA> contratos = service.getContratosXEstudio(request.getIdEstudio());
			response.setContratos(contratos);
			response.setResponseCode(code);
			
			logger.info("{}", contratos);
		} catch (Exception e) {

			logger.error("Error al invocar el servicio, request [{}] [{}]", request, e.getMessage(), e);
			code = ErrorCodes.UNKNOW_ERROR;
			ErrorUtils.setMessage(code, e.getMessage());

			response.setResponseCode(code);
		}

		if (watch.isRunning())
			watch.stop();

		logger.info("Response [{}]", response);
		logger.info("Total time [{}]", watch.getTotalTimeSeconds());

		return response;
	}

	@Override
	public ContratoResponse findDetalleContrato(ContratoRequest request) {
		logger.info("findDetalleContrato");

		TransactionState.Current().initialize();
		ErrorCodes code = ErrorCodes.SUCCESS_PROCESS;

		StopWatch watch = new StopWatch();
		watch.start();

		ContratoResponse response = new ContratoResponse();

		try {
			ContratoDDA contrato = service.getContratoDetalle(request.getIdContrato());

			List<ContratoDDA> contratos = new ArrayList<>();
			contratos.add(contrato);

			response.setContratos(contratos);
			response.setResponseCode(code);

		} catch (Exception e) {
			logger.error("Error al invocar el servicio, request [{}] [{}]", request, e.getMessage(), e);
			code = ErrorCodes.UNKNOW_ERROR;
			ErrorUtils.setMessage(code, e.getMessage());

			response.setResponseCode(code);
		}

		if (watch.isRunning())
			watch.stop();

		logger.info("Response [{}]", response);
		logger.info("Total time [{}]", watch.getTotalTimeSeconds());

		return response;

	}

}
