package com.ejie.aa21b.service;

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

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 com.ejie.aa21b.dao.Aa21b01s01Dao;
import com.ejie.aa21b.dao.ComunDao;
import com.ejie.aa21b.model.Aa21b01s01;
import com.ejie.aa21b.model.Aa21b02s01;
import com.ejie.aa21b.model.Aa21b13s01;
import com.ejie.x38.dto.JQGridRequestDto;
import com.ejie.x38.dto.JQGridResponseDto;
import com.ejie.x38.dto.JerarquiaDto;
import com.ejie.x38.dto.TableRowDto;

/**
 * Aa21b01s01ServiceImpl  
 * 
 *  
 */

@Service(value = "aa21b01s01Service")
public class Aa21b01s01ServiceImpl implements Aa21b01s01Service {

	@Autowired
	private ReloadableResourceBundleMessageSource appMessageSource;

	@Autowired
	private Aa21b01s01Dao aa21b01s01Dao;

	@Autowired
	private ComunDao comunDao;
	@Autowired
	private Aa21bAccesoPIDService pidService;

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

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

	/**
	 * Finds a single row in the Aa21b01s01 table.
	 * 
	 * @param aa21b01s01
	 *            Aa21b01s01
	 * @return Aa21b01s01
	 */
	public Aa21b01s01 find(Aa21b01s01 aa21b01s01) {
		return (Aa21b01s01) this.aa21b01s01Dao.find(aa21b01s01);
	}

	/**
	 * Deletes a single row in the Aa21b01s01 table.
	 * 
	 * @param aa21b01s01
	 *            Aa21b01s01
	 * @throws Exception
	 *             Exception
	 */
	@Transactional(rollbackFor = Throwable.class)
	public void remove(Aa21b01s01 aa21b01s01) throws Exception {
		String mensaje = "etErrorBorrarFaseExpediente";
		try {
			// Comprobamos que no exista ningún Expediente para este
			// departamento
			if (this.aa21b01s01Dao.existeFaseExpExp(aa21b01s01.getCfase01(),
					Long.parseLong(aa21b01s01.getCserv01()),
					aa21b01s01.getCtipoe01())) {
				mensaje = "etExisteExpedienteFaseExpediente";
				throw new Exception();
			} else {
				// Lo borramos del PIF y de la BD
				if (aa21b01s01.getCodPid01() != null
						&& aa21b01s01.getCodPid01().length() > 0) {
					this.pidService.delete(aa21b01s01.getCodPid01());
				}

				// this.aa21b01s01Dao.removeDocumentoFase(aa21b01s01);
				this.aa21b01s01Dao.remove(aa21b01s01);
			}
		} catch (Exception e) {
			throw new Exception(this.appMessageSource.getMessage(mensaje, null,
					LocaleContextHolder.getLocale()));
		}
	}

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

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

	/*
	 * OPERACIONES RUP_TABLE
	 */

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

	/**
	 * Filter method in the Aa21b01s01 table.
	 * 
	 * @param filterAa21b01s01
	 *            Aa21b01s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param listaServicios
	 *            List<Aa21b13s01>
	 * @param listaTiposExpedientes
	 *            List<Aa21b02s01>
	 * @param startsWith
	 *            Boolean
	 * @return JQGridResponseDto<Aa21b01s01>
	 */
	public JQGridResponseDto<Aa21b01s01> filter(Aa21b01s01 filterAa21b01s01,
			JQGridRequestDto jqGridRequestDto, List<Aa21b13s01> listaServicios,
			List<Aa21b02s01> listaTiposExpedientes, Boolean startsWith) {
		List<Aa21b01s01> listaAa21b01s01 = this.aa21b01s01Dao.findAllLike(
				filterAa21b01s01, jqGridRequestDto, listaServicios,
				listaTiposExpedientes, false);
		Long recordNum = this.aa21b01s01Dao.findAllLikeCount(
				filterAa21b01s01 != null ? filterAa21b01s01 : new Aa21b01s01(),
				listaServicios, listaTiposExpedientes, false);
		if (jqGridRequestDto.getMultiselection().getSelectedIds() != null) {
			List<TableRowDto<Aa21b01s01>> reorderSelection = this.aa21b01s01Dao
					.reorderSelection(filterAa21b01s01, jqGridRequestDto,
							startsWith);
			return new JQGridResponseDto<Aa21b01s01>(jqGridRequestDto,
					recordNum, listaAa21b01s01, reorderSelection);
		}
		return new JQGridResponseDto<Aa21b01s01>(jqGridRequestDto, recordNum,
				listaAa21b01s01);
	}

	/**
	 * Searches rows in the Aa21b01s01 table.
	 * 
	 * @param filterAa21b01s01
	 *            Aa21b01s01
	 * @param searchAa21b01s01
	 *            Aa21b01s01
	 * @param jqGridRequestDto
	 *            JQGridRequestDto
	 * @param startsWith
	 *            Boolean
	 * @return List<TableRowDto<Aa21b01s01>>
	 */
	public List<TableRowDto<Aa21b01s01>> search(Aa21b01s01 filterAa21b01s01,
			Aa21b01s01 searchAa21b01s01, JQGridRequestDto jqGridRequestDto,
			Boolean startsWith) {
		return this.aa21b01s01Dao.search(filterAa21b01s01, searchAa21b01s01,
				jqGridRequestDto, startsWith);
	}

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

	/*
	 * OPERACIONES RUP_TABLE JERARQUIA
	 */

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

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

	/**
	 * @param id
	 *            String return
	 * @return boolean
	 */
	public boolean bloquear(String id) {

		return this.comunDao.bloquear("cserv01||'-'||ctipoe01||'-'||cfase01",
				id.toString());
	}

	/**
	 * @param id
	 *            String
	 * @return boolean
	 */
	public boolean desbloquear(String id) {

		return this.comunDao.desbloquear(
				"cserv01||'-'||ctipoe01||'-'||cfase01", id.toString());
	}

	/**
	 * Updates a single row in the Aa21b12s01 table.
	 * 
	 * @param aa21b01s01
	 *            Aa21b01s01
	 * @return Aa21b01s01
	 */
	@Transactional(rollbackFor = Throwable.class)
	public Aa21b01s01 updateBloqueos(Aa21b01s01 aa21b01s01) {
		return this.aa21b01s01Dao.updateBloqueos(aa21b01s01);
	}

	@Override
	public List<Aa21b01s01> findFase(Aa21b01s01 faseExp, Boolean c) {
		// TODO Auto-generated method stub
		return this.aa21b01s01Dao.findFase(faseExp, c);
	}

	@Override
	public void updateDocumentoFase(Aa21b01s01 aa21b01s01) {
		// TODO Auto-generated method stub
		// this.aa21b01s01Dao.updateDocumentoFase(aa21b01s01);
		try {
			// modifica el fichero en el PID
			pidService.modify(aa21b01s01.getDocumentoPID(),
					aa21b01s01.getCodPid01(), aa21b01s01.getExtdocu01());

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public Aa21b01s01 addDocumentoFase(Aa21b01s01 aa21b01s01) throws Exception {
		String mensaje = "etErrorGuardandoDocumentoAsociadoFase";
		// TODO Auto-generated method stub
		try {

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

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

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

	}

	@Override
	public void compruebaBloqueosServicio(Aa21b01s01 aa21b01s01Aux)
			throws Exception {
		String mensaje = "etErrorComprobandoBloqueosFaseExpediente";
		try {
			// Comprobamos que no exista ningún Expediente para este
			// departamento

			if (this.aa21b01s01Dao
					.compruebaBloqueosFasePorServicio(aa21b01s01Aux)) {
				mensaje = "etExisteBloqueoFaseExpediente";

				this.comunDao
						.desbloquear("cserv13", aa21b01s01Aux.getCserv01());
				throw new Exception();
			}
		} catch (Exception e) {
			throw new Exception(this.appMessageSource.getMessage(mensaje, null,
					LocaleContextHolder.getLocale()));
		}

	}

	@Override
	public void updateEstadosServicio(Aa21b01s01 aa21b01s01Aux) {
		this.aa21b01s01Dao.updateEstadosServicio(aa21b01s01Aux);

	}

	@Override
	public Aa21b01s01 findDocumentoFase(Aa21b01s01 aa21b01s01) {
		// TODO Auto-generated method stub
		Aa21b01s01 temp = this.aa21b01s01Dao.findDocumentoFase(aa21b01s01);
		try {
			// obtenemos del PID el documento por el identificador
			temp.setDocumentoPID(pidService.load(temp.getCodPid01()));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return temp;
	}

	@Override
	public void removeFasesServicio(Aa21b01s01 aa21b01s01) {
		// TODO Auto-generated method stub
		this.aa21b01s01Dao.removeFasesServicio(aa21b01s01);
	}

	@Override
	public void removeFasesTipoServicio(Aa21b02s01 aa21b02s01) {
		// TODO Auto-generated method stub
		this.aa21b01s01Dao.removeFasesTipoServicio(aa21b02s01);
	}

}
