package br.com.centralit.citcorpore.ajaxForms;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citcorpore.bean.UploadDTO;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.Enumerados.CampoUpload;
import br.com.centralit.citcorpore.util.Enumerados.SimNao;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilStrings;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class UploadContrato extends AjaxFormAction {
	@Override
	public Class<UploadDTO> getBeanClass() {
		return UploadDTO.class;
	}

	@Override
	public void load(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		final br.com.centralit.citcorpore.util.Upload upload = new br.com.centralit.citcorpore.util.Upload();
		Collection<Object> colUploadsGED = null;

		HashMap hshRetorno[] = new HashMap[2];
		hshRetorno = upload.doUploadAll(request);

		if (hshRetorno[0] != null) {
			final Collection fileItems = hshRetorno[1].values();
			final HashMap formItems = hshRetorno[0];

			String itemDetalheAnexo = (String) formItems.get(CampoUpload.UPLOADCONTRATO.getNome());

			String nameUploadFile = this.definirNomeArquivoUpload(formItems);
			nameUploadFile = this.montarNomeCorporeUtil(nameUploadFile);
			final String notaTecnicaUpload = this.montarNotaTecnicaArquivo(formItems);
			colUploadsGED = this.definirColunasUpload(request);
			this.montandoPastaDeArquivos();
			this.montarItensUploadNaPastaTemp(request, colUploadsGED, fileItems, nameUploadFile, itemDetalheAnexo, notaTecnicaUpload, itemDetalheAnexo);
		}

		request.getSession(true).setAttribute(CampoUpload.UPLOADCONTRATO.getColUploadGED(), colUploadsGED);
	}

	private void montarItensUploadNaPastaTemp(final HttpServletRequest request, final Collection<Object> colUploadsGED, final Collection fileItems, final String nameUploadFile,
			final String descUploadFile, final String notaTecnicaUpload, final String itemCombo) throws Exception {
		FileItem itensUplodCompare;
		if (!fileItems.isEmpty()) {
			final Iterator it = fileItems.iterator();
			while (it.hasNext()) {
				itensUplodCompare = (FileItem) it.next();
				if (itensUplodCompare.getSize() > 0 && (itensUplodCompare.getFieldName() != null && itensUplodCompare.getFieldName().equalsIgnoreCase("file_uploadContrato"))) {
					final UploadDTO uploadDTO = new UploadDTO();
					montarUploadDTO(request, nameUploadFile, descUploadFile, notaTecnicaUpload, itensUplodCompare, uploadDTO, itemCombo);
					colUploadsGED.add(uploadDTO);
				}
			}
		}
	}

	private void montarUploadDTO(final HttpServletRequest request, final String nameUploadFile, final String descUploadFile, final String notaTecnicaUpload, FileItem itensUploda,
			final UploadDTO uploadDTO, final String itemCombo) throws Exception {
		File arquivo;
		uploadDTO.setDescricao(itemCombo);
		uploadDTO.setTipoAnexoParaCombo(descUploadFile);
		uploadDTO.setNameFile(nameUploadFile);
		uploadDTO.setSituacao(UtilI18N.internacionaliza(request, "citcorpore.comum.temporario"));
		uploadDTO.setTemporario(SimNao.SIM.getValorStr());
		uploadDTO.setNotaTecnicaUpload(notaTecnicaUpload);
		uploadDTO.setPath(CITCorporeUtil.CAMINHO_REAL_APP + "tempUpload/" + uploadDTO.getNameFile());

		arquivo = new File(uploadDTO.getPath());
		itensUploda.write(arquivo);
	}

	private void montandoPastaDeArquivos() {
		final File f = new File(CITCorporeUtil.CAMINHO_REAL_APP + "tempUpload");
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	private Collection<Object> definirColunasUpload(final HttpServletRequest request) {
		Collection<Object> colUploadsGED;
		colUploadsGED = (Collection) request.getSession(true).getAttribute(CampoUpload.UPLOADCONTRATO.getColUploadGED());
		if (colUploadsGED == null || colUploadsGED.isEmpty()) {
			colUploadsGED = new ArrayList();
		}
		return colUploadsGED;
	}

	private String montarNotaTecnicaArquivo(final HashMap formItems) {
		String notaTecnicaUpload = (String) formItems.get("NOTATECNICAUPLOAD");
		if (notaTecnicaUpload == null) {
			notaTecnicaUpload = SimNao.NAO.getValorStr();
		}
		return notaTecnicaUpload;
	}

	private String montarNomeCorporeUtil(String nameUploadFile) {
		if (nameUploadFile != null) {
			nameUploadFile = CITCorporeUtil.getNameFile(nameUploadFile);
		}
		return nameUploadFile;
	}

	private String definirNomeArquivoUpload(final HashMap formItems) throws UnsupportedEncodingException {
		String nameUploadFile = (String) formItems.get("FILE_UPLOADCONTRATO");
		nameUploadFile = UtilStrings.nullToVazio(nameUploadFile);
		
		if (nameUploadFile.trim().equalsIgnoreCase("arquivo")) {
			nameUploadFile = (String) formItems.get("FILE_UPLOADANEXOS");
			nameUploadFile = UtilStrings.decodeCaracteresEspeciais(nameUploadFile);
			
		}

		return nameUploadFile;
	}

}