package com.ejie.aa21b.service;

import java.net.MalformedURLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.ejie.aa21b.dao.Aa21b25s01Dao;
import com.ejie.aa21b.model.Aa21b25s01;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.JQGridResponseDto;
import com.ejie.x38.dto.JerarquiaDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * Aa21b25s01ServiceImpl  
 * 
 *  
 */

@Service(value = "aa21b25s01Service")
public class Aa21b25s01ServiceImpl implements Aa21b25s01Service {
	private static final Logger logger = LoggerFactory
			.getLogger(Aa21b25s01ServiceImpl.class);

	@Autowired
	private Aa21b25s01Dao aa21b25s01Dao;
	@Autowired
	private Aa21bAccesoPIDService pidService;

	@Autowired
	private ReloadableResourceBundleMessageSource appMessageSource;

	/**
	 * Inserts a single row in the Aa21b25s01 table.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 * @return Aa21b25s01
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b25s01 add(Aa21b25s01 aa21b25s01) {
		return this.aa21b25s01Dao.add(aa21b25s01);
	}

	/**
	 * Updates a single row in the Aa21b25s01 table.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 * @return Aa21b25s01
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b25s01 update(Aa21b25s01 aa21b25s01) {
		return this.aa21b25s01Dao.update(aa21b25s01);
	}

	/**
	 * Finds a single row in the Aa21b25s01 table.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 * @return Aa21b25s01
	 */
	public Aa21b25s01 find(Aa21b25s01 aa21b25s01) {
		return (Aa21b25s01) this.aa21b25s01Dao.find(aa21b25s01);
	}

	/**
	 * Deletes a single row in the Aa21b25s01 table.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 */
	@Transactional(rollbackFor = Throwable.class)
	public void remove(Aa21b25s01 aa21b25s01) {
		this.aa21b25s01Dao.remove(aa21b25s01);
	}

	/**
	 * Finds a list of rows in the Aa21b25s01 table.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return List<Aa21b25s01>
	 */
	public List<Aa21b25s01> findAll(Aa21b25s01 aa21b25s01,
			JQGridRequestDto jqGridRequestDto) {
		return (List<Aa21b25s01>) this.aa21b25s01Dao.findAll(aa21b25s01,
				jqGridRequestDto);
	}

	/**
	 * Finds rows in the Aa21b25s01 table using like.
	 * 
	 * @param aa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<Aa21b25s01>
	 */
	public List<Aa21b25s01> findAllLike(Aa21b25s01 aa21b25s01,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		return (List<Aa21b25s01>) this.aa21b25s01Dao.findAllLike(aa21b25s01,
				jqGridRequestDto, startsWith);
	}

	/*
	 * OPERACIONES RUP_TABLE
	 */

	/**
	 * Removes rows from the Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 */
	public void removeMultiple(Aa21b25s01 filterAa21b25s01,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		this.aa21b25s01Dao.removeMultiple(filterAa21b25s01, jqGridRequestDto,
				startsWith);
	}

	/**
	 * Filter method in the Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return JQGridResponseDto<Aa21b25s01>
	 */
	public JQGridResponseDto<Aa21b25s01> filter(Aa21b25s01 filterAa21b25s01,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		List<Aa21b25s01> listaAa21b25s01 = this.aa21b25s01Dao.findAllLike(
				filterAa21b25s01, jqGridRequestDto, false);
		Long recordNum = this.aa21b25s01Dao.findAllLikeCount(
				filterAa21b25s01 != null ? filterAa21b25s01 : new Aa21b25s01(),
				false);
		if (jqGridRequestDto.getMultiselection().getSelectedIds() != null) {
			List<TableRowDto<Aa21b25s01>> reorderSelection = this.aa21b25s01Dao
					.reorderSelection(filterAa21b25s01, jqGridRequestDto,
							startsWith);
			return new JQGridResponseDto<Aa21b25s01>(jqGridRequestDto,
					recordNum, listaAa21b25s01, reorderSelection);
		}
		return new JQGridResponseDto<Aa21b25s01>(jqGridRequestDto, recordNum,
				listaAa21b25s01);
	}

	/**
	 * Searches rows in the Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param searchAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<TableRowDto<Aa21b25s01>>
	 */
	public List<TableRowDto<Aa21b25s01>> search(Aa21b25s01 filterAa21b25s01,
			Aa21b25s01 searchAa21b25s01, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		return this.aa21b25s01Dao.search(filterAa21b25s01, searchAa21b25s01,
				jqGridRequestDto, startsWith);
	}

	/**
	 * Reorder the selection made in Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return Object
	 */
	public Object reorderSelection(Aa21b25s01 filterAa21b25s01,
			JQGridRequestDto jqGridRequestDto, Boolean startsWith) {
		return this.aa21b25s01Dao.reorderSelection(filterAa21b25s01,
				jqGridRequestDto, startsWith);
	}

	/*
	 * OPERACIONES RUP_TABLE JERARQUIA
	 */

	/**
	 * Finder method in the hierarchical the Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return JQGridResponseDto<JerarquiaDto<Aa21b25s01>>
	 */
	public JQGridResponseDto<JerarquiaDto<Aa21b25s01>> jerarquia(
			Aa21b25s01 filterAa21b25s01, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		List<JerarquiaDto<Aa21b25s01>> listaAa21b25s01 = this.aa21b25s01Dao
				.findAllLikeJerarquia(filterAa21b25s01, jqGridRequestDto);
		Long recordNum = this.aa21b25s01Dao.findAllLikeCountJerarquia(
				filterAa21b25s01, jqGridRequestDto);
		return new JQGridResponseDto<JerarquiaDto<Aa21b25s01>>(
				jqGridRequestDto, recordNum, listaAa21b25s01);
	}

	/**
	 * Finder method for siblings rows in the hierarchical the Aa21b25s01 table.
	 * 
	 * @param filterAa21b25s01
	 *            Aa21b25s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @return JQGridResponseDto<JerarquiaDto<Aa21b25s01>>
	 */
	public JQGridResponseDto<JerarquiaDto<Aa21b25s01>> jerarquiaChildren(
			Aa21b25s01 filterAa21b25s01, JQGridRequestDto jqGridRequestDto) {
		JQGridResponseDto<JerarquiaDto<Aa21b25s01>> jqGridResponseDto = new JQGridResponseDto<JerarquiaDto<Aa21b25s01>>();
		jqGridResponseDto.addAdditionalParam(JQGridResponseDto.CHILDREN,
				this.aa21b25s01Dao.findAllChild(filterAa21b25s01,
						jqGridRequestDto));
		return jqGridResponseDto;
	}

	/**
	 * Guarda el fichero en el PID y actualiza la entidad
	 * 
	 * @param entidad
	 * @param docu05
	 * @return
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b25s01 guardarFicheroActualizarEntidad(Aa21b25s01 entidad,
			MultipartFile docu05) {
		Aa21b25s01ServiceImpl.logger
				.info("Guardar Fichero en el PID y actualizar la entidad");
		// guarda el documento en PID y obtiene el identificador del PID
		try {
			entidad = this.aa21b25s01Dao.find(entidad);
			int id = docu05.getOriginalFilename().lastIndexOf(".");
			String ext = docu05.getOriginalFilename().substring(id + 1);
			String idPID = pidService.saveNew(docu05.getBytes(),
					System.currentTimeMillis() + "", ext);
			entidad.setCodpid25(idPID);
			entidad.setExtdocu25(ext);
			entidad.setCtype25(docu05.getContentType());
			this.aa21b25s01Dao.update(entidad);

		} catch (Exception e) {

			Aa21b25s01ServiceImpl.logger.error(e.getMessage());
			StackTraceElement[] traces = e.getStackTrace();
			for (StackTraceElement el : traces) {
				Aa21b25s01ServiceImpl.logger.error(el.toString());
			}
		}

		return entidad;
	}

	/**
	 * Actualiza el fichero en el PID y actualiza la entidad
	 * 
	 * @param entidad
	 * @param docu05
	 * @return
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b25s01 actualizarFicheroActualizarEntidad(Aa21b25s01 entidad,
			MultipartFile docu05) {
		Aa21b25s01ServiceImpl.logger
				.info("Actualiza Fichero en el PID y actualizar la entidad");
		// guarda el documento en PID y obtiene el identificador del PID
		try {
			entidad = this.aa21b25s01Dao.find(entidad);
			String ext = docu05.getOriginalFilename().split("\\.")[1];
			pidService.modify(docu05.getBytes(), entidad.getCodpid25(), ext);
			entidad.setExtdocu25(ext);
			entidad.setCtype25(docu05.getContentType());
			this.aa21b25s01Dao.update(entidad);

		} catch (Exception e) {

			Aa21b25s01ServiceImpl.logger.error(e.getMessage());
			StackTraceElement[] traces = e.getStackTrace();
			for (StackTraceElement el : traces) {
				Aa21b25s01ServiceImpl.logger.error(el.toString());
			}
		}

		return entidad;
	}

	/**
	 * Borra el fichero en el PID y actualiza la entidad
	 * 
	 * @param entidad
	 * @param docu05
	 * @return
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b25s01 borraFicheroActualizarEntidad(Aa21b25s01 entidad) {
		Aa21b25s01ServiceImpl.logger
				.info("borra Fichero en el PID y actualizar la entidad");
		// guarda el documento en PID y obtiene el identificador del PID
		try {
			entidad = this.aa21b25s01Dao.find(entidad);

			pidService.delete(entidad.getCodpid25());
			entidad.setExtdocu25("");
			entidad.setCodpid25("");
			this.aa21b25s01Dao.update(entidad);

		} catch (Exception e) {

			Aa21b25s01ServiceImpl.logger.error(e.getMessage());
			StackTraceElement[] traces = e.getStackTrace();
			for (StackTraceElement el : traces) {
				Aa21b25s01ServiceImpl.logger.error(el.toString());
			}
		}

		return entidad;
	}

	@Override
	public Aa21b25s01 findDocExpediente(Aa21b25s01 aa21b25s01) {
		// TODO Auto-generated method stub
		Aa21b25s01 temp = this.aa21b25s01Dao.findDocExpediente(aa21b25s01);
		try {
			temp.setDocumentoPID(pidService.load(temp.getCodpid25()));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return temp;
	}

	@Override
	public Aa21b25s01 addDocumentoExpediente(Aa21b25s01 aa21b25s01)
			throws Exception {
		String mensaje = "etErrorGuardandoDocumentoExpediente";
		// TODO Auto-generated method stub
		try {

			// guarda el documento en PID y obtiene el identificador del PID
			String idPID = pidService.saveNew(aa21b25s01.getDocumentoPID(),
					System.currentTimeMillis() + "", aa21b25s01.getExtdocu25());

			// guarda en la tabla el el identificador del documento y el
			// identificador del PID
			if (idPID != null) {
				aa21b25s01.setCodpid25(idPID);
				// this.aa21b01s01Dao.updateDocumentoFase(aa21b01s01);

				return aa21b25s01;
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new Exception(this.appMessageSource.getMessage(mensaje, null,
					LocaleContextHolder.getLocale()));
		}

	}

}
