package com.ejie.ab39a.service;

import com.ejie.ab39a.dao.ElementosArbolDao;
import com.ejie.ab39a.dao.PlanesEstrategicosDao;
import com.ejie.ab39a.dao.PlanesGestionDao;
import com.ejie.x38.dto.JQGridRequestDto;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ejie.ab39a.model.AccionesPg;
import com.ejie.ab39a.model.EjePe;
import com.ejie.ab39a.model.ElementosArbol;
import com.ejie.ab39a.model.ElementosPe;
import com.ejie.ab39a.model.PlanesEstrategicos;
import com.ejie.ab39a.model.PlanesGestion;
import com.ejie.ab39a.utils.Utilidades;

/**
 * ElementosPe.
 * 
 *  
 */
@Service(value = "elementosArbolService")
public class ElementosArbolServiceImpl implements ElementosArbolService {

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

	@Autowired
	private ElementosArbolDao elementosArbolDao;
	@Autowired
	private PlanesEstrategicosDao planesEstrategicosDao;
	@Autowired
	private AccionesPgService accionesPgService;

	@Autowired
	private PlanesEstrategicosService planesEstrategicosService;

	@Autowired
	private PlanesGestionDao planesGestionDao;

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public List<ElementosArbol> findAll(Integer idPE, Integer version, JQGridRequestDto jqGridRequestDto) {
		return this.elementosArbolDao.findAll(idPE, version, jqGridRequestDto);
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public List<ElementosArbol> findAllGestion(Integer idPE, JQGridRequestDto jqGridRequestDto) {

		return this.elementosArbolDao.findAllGestion(idPE, jqGridRequestDto);
	}

	/**
	 * Updates a single row in the ElementosPe table.
	 *
	 * @param elem
	 *            ElementosArbol
	 */

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
	public void guardarHelburu(ElementosArbol elem) {
		this.elementosArbolDao.guardarHelburu(elem);
	}

	/**
	 * Updates a single row in the ElementosPe table.
	 *
	 * @param elem
	 *            ElementosArbol
	 */

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
	public void guardarTituloPG(ElementosArbol elem) {

		this.planesGestionDao.updateActualizar(elem);

		this.elementosArbolDao.guardarTituloPG(elem);
	}

	/**
	 * Borra elementos de nivel 3 del arbol
	 *
	 * @param elementoId
	 *            long
	 */

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Throwable.class)
	public void borrarElemento(Long elementoId, PlanesEstrategicos planEstrategico) {

		this.elementosArbolDao.borrarElemento(elementoId);

		this.planesEstrategicosService.solicitarInformeNo(planEstrategico);
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public ElementosArbol elementoNuevo(ElementosPe elem) {
		ElementosArbol elemArbol = this.elementosArbolDao.elementoNuevo(elem);

		PlanesEstrategicos planes = new PlanesEstrategicos();
		planes.setCodplane(elem.getCodPlaneA().intValue());
		planes.setCodVersion(elem.getVersion().intValue());
		this.planesEstrategicosService.solicitarInformeNo(planes);

		return elemArbol;
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public ElementosArbol elementoNuevoNivel4(ElementosArbol elem, AccionesPg accion) {
		PlanesGestion pg = new PlanesGestion();
		pg.setCodplang(elem.getCodPlaneA().intValue());
		this.planesGestionDao.updateActualizar(pg);
		return this.elementosArbolDao.elementoNuevoNivel4(elem, accion);
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public void modificarElemento(ElementosArbol elem) {

		this.elementosArbolDao.modificarElemento(elem);

		PlanesEstrategicos planes = new PlanesEstrategicos();
		planes.setCodplane(elem.getCodPlaneA().intValue());
		planes.setCodVersion(elem.getVersion().intValue());
		this.planesEstrategicosService.solicitarInformeNo(planes);

	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public void editarOharrak(ElementosPe elem) {
		this.elementosArbolDao.editarOharrak(elem);
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param idPE
	 *            Integer
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<ElementosArbol>
	 */
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public Map<String, Object> findAllVersion(Integer idPE, Integer version, JQGridRequestDto jqGridRequestDto) {

		List<ElementosArbol> listaArbolVersion = this.elementosArbolDao.findAll(idPE, version, jqGridRequestDto);
		Map<String, Object> mapaDatos = new HashMap<String, Object>();
		if (version != 1) {
			// Buscamos datos de la version anterior
			Map<Long, EjePe> listaEjesVersionAnterior = this.elementosArbolDao.findAllEjesVersionAnterior(idPE, version,
					jqGridRequestDto);

			Map<Long, ElementosPe> listaElementosVersionAnterior = this.elementosArbolDao.findAllVersionAnterior(idPE,
					version, jqGridRequestDto);
			mapaDatos = Utilidades.compararPlanes(listaArbolVersion, listaElementosVersionAnterior,
					listaEjesVersionAnterior);
		} else {
			mapaDatos.put("listaArbol", listaArbolVersion);
			mapaDatos.put("listaElemBorrados", new ArrayList<ElementosArbol>());
		}

		return mapaDatos;
	}

	/**
	 * Finds a list of rows in the ElementosPe table.
	 *
	 * @param planE
	 *            PlanesEstrategicos
	 * @param consulta
	 *            Integer
	 * @return Map<String, Object>
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Transactional(propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED)
	public Map<String, Object> datosArbolPlanE(PlanesEstrategicos planE, Integer consulta) {
		Map<String, Object> mapaDatos = new HashMap<String, Object>();
		List<ElementosArbol> listaElemBorrados = new ArrayList<ElementosArbol>();
		List<ElementosArbol> lista = new ArrayList<ElementosArbol>();

		PlanesEstrategicos plan = this.planesEstrategicosDao.find(planE);
		Long tienePg = this.planesEstrategicosDao.borraPlanTieneGestion(planE);

		if (consulta == 0) {
			lista = this.elementosArbolDao.findAll(planE.getCodplane(), planE.getCodVersion(), null);
		} else {
			Map<String, Object> mapa = this.findAllVersion(planE.getCodplane(), planE.getCodVersion(), null);
			lista = (List<ElementosArbol>) mapa.get("listaArbol");
			listaElemBorrados = (List<ElementosArbol>) mapa.get("listaElemBorrados");
		}
		mapaDatos.put("tienePg", tienePg);
		mapaDatos.put("solicitudTxostena", plan.getSolitudTxostena());
		mapaDatos.put("datosPlan", plan);
		mapaDatos.put("lista", lista);
		mapaDatos.put("listaElemBorrados", listaElemBorrados);

		return mapaDatos;
	}

	/**
	 * Inserta nuevas acciones
	 * 
	 * @param lista
	 *            List<AccionesPg>
	 * @param modo
	 *            String tipo de nueva accion, seleccionada o creada
	 * @return List<AccionesPg> lista de acciones
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
	public List<AccionesPg> insertarNuevasAcciones(List<AccionesPg> lista, String modo) {
		ElementosArbolServiceImpl.logger.debug("Entrando en insertarNuevasAcciones");

		if (lista == null || lista.isEmpty()) {
			ElementosArbolServiceImpl.logger.debug("insertarNuevasAcciones: lista es NULO o Vacio");
			return lista;
		}
		List<AccionesPg> listaDev = new ArrayList<AccionesPg>();
		for (AccionesPg accion : lista) {
			listaDev.add(this.accionesPgService.anyadirAccionPgNueva(accion, modo));
		}
		ElementosArbolServiceImpl.logger.debug("Saliendo de insertarNuevasAcciones");
		return listaDev;
	}

}