package com.ejie.ab79.webservice.adaptadores;

import java.io.BufferedInputStream;
import java.io.InputStream;

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

import com.ejie.ab79.comun.Constantes;
import com.ejie.ab79.comun.UtilsXlnets;
import com.ejie.ab79.exceptions.PifException;
import com.ejie.ab79.webservice.PifService;
import com.ejie.y31.vo.Y31AttachmentBean;

/**
 * 
 *  
 *
 */

@Service(value = "PIFAdaptadorImpl")
public class PIFAdaptadorImpl implements PIFAdaptador {

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

	@Autowired
	public PifService pifService;

	/**
	 * Clase que adaptara los servicios de PIF a nuestro sistema
	 */
	private PIFAdaptadorImpl() {
		super();
	}

	/**
	 * Obtener documento a PIF
	 * 
	 * @param file
	 *            Fichero que se va a subir al PIF
	 * @param fileName
	 *            Nombre del fichero
	 * @return
	 * @throws NumberFormatException
	 * @throws PifException
	 */
	@Override
	public BufferedInputStream getFile(String pathFrom) throws NumberFormatException, PifException {

		return (BufferedInputStream) this.pifService.getFile(UtilsXlnets.getInstance().getTokenAplicacionDocument(),
				pathFrom);

	}

	/**
	 * Subir documento a PIF
	 *
	 * @param file
	 *            Fichero que se va a subir al PIF para posteriormente subir a
	 *            PID
	 * @param fileName
	 *            Nombre del fichero
	 * @return String
	 * @throws PifException
	 */
	@Override()
	public String putFileToPID(InputStream file, String fileName) throws PifException {
		PIFAdaptadorImpl.logger.info("putFileToPID - Inicio");
		try {
			String pathTo = "/" + Constantes.PIF_CARPETA_PID + "/" + Constantes.CODIGO_APLICACION + "/" + fileName;
			Y31AttachmentBean y31AttachmentBeanResult = this.pifService.putFile(
					UtilsXlnets.getInstance().getTokenAplicacionDocument(), file, pathTo, true,
					Long.valueOf(Constantes.PIF_TIEMPO_EXISTENCIA));
			return y31AttachmentBeanResult.getFilePath();
		} catch (PifException ePIF) {
			throw ePIF;
		} catch (Exception excep) {
			throw new PifException(excep.getMessage());
		} finally {
			PIFAdaptadorImpl.logger.info("putFileToPID - Final");
		}
	}

}
