package com.ejie.ab79.service;

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.transaction.annotation.Transactional;

import com.ejie.ab79.dao.RelOriDirDao;
import com.ejie.ab79.model.RelOriDir;
import com.ejie.x38.dto.TableRequestDto;
import com.ejie.x38.dto.TableResponseDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * RelEstInsServiceImpl  
 * 
 *  
 */

@Service(value = "relOriDirService")
public class RelOriDirServiceImpl implements RelOriDirService {

	@Autowired
	private RelOriDirDao relOriDirDao;

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

	@Transactional(rollbackFor = Throwable.class)
	public RelOriDir update(RelOriDir relOriDir) {
		return this.relOriDirDao.update(relOriDir);
	}

	public RelOriDir find(RelOriDir relOriDir) {
		return this.relOriDirDao.find(relOriDir);
	}

	public List<RelOriDir> findAll(RelOriDir relOriDir, TableRequestDto tableRequestDto) {
		return this.relOriDirDao.findAll(relOriDir, tableRequestDto);
	}

	public List<RelOriDir> findAllLike(RelOriDir relOriDir, TableRequestDto tableRequestDto, Boolean startsWith) {
		return this.relOriDirDao.findAllLike(relOriDir, tableRequestDto, startsWith);
	}

	public TableResponseDto<RelOriDir> filter(RelOriDir filterRelOriDir, TableRequestDto tableRequestDto,
			Boolean startsWith) {
		List<RelOriDir> listaRelEstIns = this.relOriDirDao.findAllLike(filterRelOriDir, tableRequestDto, false);
		Long recordNum = this.relOriDirDao.findAllLikeCount(filterRelOriDir != null ? filterRelOriDir : new RelOriDir(),
				false);

		TableResponseDto<RelOriDir> usuarioDto = new TableResponseDto<RelOriDir>(tableRequestDto, recordNum,
				listaRelEstIns);

		if (tableRequestDto.getMultiselection().getSelectedIds() != null) {
			List<TableRowDto<RelOriDir>> reorderSelection = this.relOriDirDao.reorderSelection(filterRelOriDir,
					tableRequestDto, startsWith);
			usuarioDto.setReorderedSelection(reorderSelection);
			usuarioDto.addAdditionalParam("reorderedSelection", reorderSelection);
			usuarioDto.addAdditionalParam("selectedAll", tableRequestDto.getMultiselection().getSelectedAll());
		}
		if (tableRequestDto.getSeeker().getSelectedIds() != null) {
			tableRequestDto.setMultiselection(tableRequestDto.getSeeker());
			List<TableRowDto<RelOriDir>> reorderSeeker = this.relOriDirDao.reorderSelection(filterRelOriDir,
					tableRequestDto, startsWith);
			usuarioDto.setReorderedSeeker(reorderSeeker);
			usuarioDto.addAdditionalParam("reorderedSeeker", reorderSeeker);
		}

		logger.info("[filter] Elementos obtenidos correctamente");
		return usuarioDto;
	}

	@Override
	public RelOriDir findByOrigenDireccion(RelOriDir relOriDir) {
		return this.relOriDirDao.findByOrigenDireccion(relOriDir);
	}

}
