package com.ejie.ab79.control;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.ejie.ab79.clientesWS.ab61WebService.Ab61Exception;
import com.ejie.ab79.clientesWS.ab61WebService.Usuario;
import com.ejie.ab79.comun.Constantes;
import com.ejie.ab79.model.DocumentosSubidos;
import com.ejie.ab79.model.RelCamDoc;
import com.ejie.ab79.service.RelCamDocService;
import com.ejie.ab79.webservice.adaptadores.PIFAdaptador;
import com.ejie.ab79.webservice.adaptadores.ab61WebServiceAdaptador;
import com.ejie.x38.control.bind.annotation.RequestJsonBody;
import com.ejie.x38.dto.TableRequestDto;
import com.ejie.x38.dto.TableResponseDto;

/**
 * RelCamDocController  
 * 
 *  
 */

@Controller
@RequestMapping(value = "/relcamdoc")
@SessionAttributes("usuario")
public class RelCamDocController {

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

	@Autowired
	private RelCamDocService relCamDocService;

	@Autowired
	private ab61WebServiceAdaptador ab61WebServiceAdaptadorService;

	@Autowired
	private PIFAdaptador pifAdapterService;

	@RequestMapping(value = "/{idRelCamDoc}", method = RequestMethod.GET)
	public @ResponseBody RelCamDoc get(@PathVariable Integer idRelCamDoc) {
		RelCamDoc relCamDoc = new RelCamDoc();
		relCamDoc.setIdRelCamDoc(idRelCamDoc);
		relCamDoc = this.relCamDocService.find(relCamDoc);
		RelCamDocController.logger.info("[GET - findBy_PK] : Obtener RelCamDoc por PK");
		return relCamDoc;
	}

	@RequestMapping(method = RequestMethod.GET)
	public @ResponseBody List<RelCamDoc> getAll(@ModelAttribute RelCamDoc filterRelCamDoc) {
		RelCamDocController.logger.info("[GET - find_ALL] : Obtener RelCamDoc por filtro");
		return this.relCamDocService.findAll(filterRelCamDoc, null);
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody RelCamDoc add(@RequestBody RelCamDoc relCamDoc) {
		RelCamDoc relCamDocAux = this.relCamDocService.add(relCamDoc);
		RelCamDocController.logger.info("[POST] : RelCamDoc insertado correctamente");
		return relCamDocAux;
	}

	@RequestMapping(value = "/subirDocumento", method = RequestMethod.POST)
	public @ResponseBody RelCamDoc add(@ModelAttribute("relcamdoc") RelCamDoc relcamdoc,
			@ModelAttribute("usuario") Usuario usuario,
			@RequestParam(value = "file", required = true) MultipartFile file) throws Ab61Exception {

		this.relCamDocService.subidaPidInsertar(relcamdoc, file, usuario);

		return relcamdoc;
	}

	@RequestMapping(value = "/{idRelCamDoc}", method = RequestMethod.DELETE)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody RelCamDoc remove(@PathVariable Integer idRelCamDoc) {
		RelCamDoc relCamDoc = new RelCamDoc();
		relCamDoc.setIdRelCamDoc(idRelCamDoc);
		this.relCamDocService.remove(relCamDoc);
		RelCamDocController.logger.info("[DELETE] : RelCamDoc borrado correctamente");
		return relCamDoc;
	}

	@RequestMapping(value = "/descargarDocumentoDokusi/{oidDokusi}/{nombreDocumento:.+}", method = RequestMethod.GET)
	public @ResponseBody void descargarDocumentoDokusi(@PathVariable String oidDokusi,
			@PathVariable String nombreDocumento, HttpServletResponse response) throws IOException {

		BufferedInputStream bIS = null;
		try {
			String pathPif = this.ab61WebServiceAdaptadorService.descargarDocumentoDokusi(oidDokusi,
					Constantes.CODIGO_APLICACION, Constantes.TIPO_URL_PARCIAL);

			if (!StringUtils.isEmpty(pathPif)) {
				response.setHeader("content-disposition", "attachment; filename=\"" + nombreDocumento + "\"");
			}

			bIS = new BufferedInputStream(this.pifAdapterService.getFile(pathPif));
			IOUtils.copy(bIS, response.getOutputStream());
			response.flushBuffer();
		} catch (Exception e) {
			RelCamDocController.logger.error("descargarDocumentoDokusi - ERROR", e);
		} finally {
			if (bIS != null) {
				bIS.close();
			}
		}
	}

	@RequestMapping(value = "/descargarDocumentoPid/{oidPid}/{nombreDocumento:.+}", method = RequestMethod.GET)
	public @ResponseBody void descargarDocumentoPid(@PathVariable String oidPid, @PathVariable String nombreDocumento,
			HttpServletResponse response) throws IOException {

		BufferedInputStream bIS = null;
		try {
			String pathPif = this.ab61WebServiceAdaptadorService.descargarDocumentoPid(oidPid,
					Constantes.CODIGO_APLICACION, Constantes.TIPO_URL_PARCIAL);

			if (!StringUtils.isEmpty(pathPif)) {
				response.setHeader("content-disposition", "attachment; filename=\"" + nombreDocumento + "\"");
				bIS = new BufferedInputStream(this.pifAdapterService.getFile(pathPif));
				IOUtils.copy(bIS, response.getOutputStream());
				response.flushBuffer();
			}

			RelCamDocController.logger.info("descargarDocumentoPid : " + pathPif);
		} catch (Exception e) {
			RelCamDocController.logger.error("descargarDocumentoPid - ERROR", e);
		} finally {
			if (bIS != null) {
				bIS.close();
			}
		}
	}

	@RequestMapping(value = "/eliminarDocumento/{idDocumentoSubido}/{oidPid}", method = RequestMethod.DELETE)
	public @ResponseBody RelCamDoc eliminarDocumento(@PathVariable Integer idDocumentoSubido,
			@PathVariable String oidPid) throws Exception {

		RelCamDoc relCamDoc = new RelCamDoc();
		relCamDoc.setDocumentoSubido(new DocumentosSubidos(idDocumentoSubido));

		// Eliminamos el documento de PID
		this.ab61WebServiceAdaptadorService.eliminarDocumentoPid(oidPid);
		RelCamDocController.logger.info("Documento eliminado de PID - " + oidPid);

		// Eliminamos el documento de BBDD
		this.relCamDocService.removeByIdDocumentoSubido(relCamDoc);
		RelCamDocController.logger.info("[DELETE] : RelCamDoc borrado correctamente");

		return relCamDoc;
	}

	@RequestMapping(value = "/maint", method = RequestMethod.GET)
	public String getFormEdit(Model model) {
		RelCamDocController.logger.info("[GET - View] : relcamdoc");
		return "relcamdoc";
	}

	@RequestMapping(value = "/filter", method = RequestMethod.POST)
	public @ResponseBody TableResponseDto<RelCamDoc> filter(
			@RequestJsonBody(param = "filter") RelCamDoc filterRelCamDoc,
			@RequestJsonBody TableRequestDto tableRequestDto) {
		RelCamDocController.logger.info("[POST - filter] : Obtener RelCamDocs");
		return this.relCamDocService.filter(filterRelCamDoc, tableRequestDto, false);
	}
}
