package br.com.centralit.citcorpore.ajaxForms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

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

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.Enumerados.CampoUpload;
import br.com.citframework.util.UtilI18N;

/**
 * @author pedro.francisco
 * @since 18.02.2016
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class UploadExcluirGenerico extends AjaxFormAction {

	public abstract CampoUpload getCampoUpload();

	public abstract void salvar(UploadDTO anexoRemovido, DocumentHTML document, HttpServletRequest request) throws Exception;

	public abstract boolean excluirAnexos(Collection<String> collectionUploadsGED, HttpServletRequest request, DocumentHTML document);

	@Override
	public Class getBeanClass() {
		return UploadDTO.class;
	}

	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		UploadDTO uploadDTO = (UploadDTO) document.getBean();

		Collection colUploadsGED = (Collection) request.getSession(true).getAttribute(getCampoUpload().getColUploadGED());
		Collection<String> collectionUploadsGED = new ArrayList<String>();

		if (colUploadsGED == null) {
			colUploadsGED = new ArrayList();
		}

		Collection<UploadDTO> anexos = new ArrayList();
		UploadDTO anexoRemovido = new UploadDTO();

		for (Iterator it = colUploadsGED.iterator(); it.hasNext();) {
			UploadDTO uploadAux = (UploadDTO) it.next();
			if (!uploadAux.getPath().equalsIgnoreCase(uploadDTO.getPath().replace("\\", "\\\\"))) {
				anexos.add(uploadAux);
			} else {
				collectionUploadsGED.add(uploadDTO.getPath());
				anexoRemovido = uploadAux;
			}
		}

		if(excluirAnexos(collectionUploadsGED, request, document)){
			if (anexoRemovido.getIdControleGED() != null) {
				salvar(anexoRemovido, document, request);
			}
			request.getSession(true).setAttribute(getCampoUpload().getColUploadGED(), anexos);
		}else{
			document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.permissaoFuncionalidade"));
		}
	}

}
