package com.mx.dla.dda.contrato.transaccion.comun.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	protected Logger logger = LoggerFactory.getLogger("app");

	private static final long serialVersionUID = 1L;
	private File fileUpload;
	private OutputStream outStream;
	private boolean bandera;
	private String contentType;
	private String filename;

	public String execute() {

		try {
			byte[] f = FileUtils.readFileToByteArray(fileUpload);
			File d = new File(filename);

			d.setExecutable(true, false);
			d.setReadable(true, false);
			d.setWritable(true, false);

			logger.debug("Absolute path [{}]  -  [{}]", d.getCanonicalPath(), d.getPath());
			FileUtils.writeByteArrayToFile(d, f);
		} catch (IOException e) {
			bandera = false;
		}

		bandera = true;
		return SUCCESS;
	}

	public String descargar() {

		try {
			byte[] result = null;
			File file = new File("C:\\Users\\bark\\Desktop\\1.xlsx");
			result = IOUtils.toByteArray(new FileInputStream(file));
			FileUtils.writeByteArrayToFile(file, result);

			HttpServletResponse response = ServletActionContext.getResponse();
			ServletOutputStream out = response.getOutputStream();
			out.write(result);
			out.flush();
		} catch (IOException e) {
			bandera = false;
		}

		bandera = true;
		return null;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public boolean isBandera() {
		return bandera;
	}

	public void setBandera(boolean bandera) {
		this.bandera = bandera;
	}

	public File getFileUpload() {
		return fileUpload;
	}

	public void setFileUpload(File fileUpload) {
		this.fileUpload = fileUpload;
	}

	public OutputStream getOutStream() {
		return outStream;
	}

	public void setOutStream(OutputStream outStream) {
		this.outStream = outStream;
	}

}
