package com.mx.dla.dda.excelMapper.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;

import com.mx.dla.dda.excelMapper.bos.ExcelMapperTransform;
import com.mx.dla.dda.excelMapper.constants.ExcelMapperConstants;
import com.mx.dla.global.actions.BaseAction;

public class ExcelMapperAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private InputStream fileInputStream;
	
	private String elements;

	@Autowired
	private ExcelMapperTransform excelMapperTransform;
	
	@Override
	public String execute() throws Exception {
		
		if( elements != null) {
			logger.trace("Datos recividos [{}]",elements);
			getSession().put(ExcelMapperConstants.MAP_SESSION,elements);
			fileInputStream = new ByteArrayInputStream(new byte[1]);
			return SUCCESS;
		}
		else {
			String map =  (String) getSession().get(ExcelMapperConstants.MAP_SESSION);
			if(map == null)
			{
				throw new Exception("No existen datos para generar el reporte");
			}
			logger.trace("Datos para genrerar excel [{}]",map);
			
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> toExcel = mapper.readValue( map, 
					new TypeReference<Map<String, Object>>() {
			});
			
			List<HashMap> rows =  (List<HashMap>) toExcel.get(ExcelMapperConstants.ROOT_ELEMENT);
			byte [] bytes = excelMapperTransform.transformMapToExcel(rows);
			fileInputStream = new ByteArrayInputStream(bytes);
			return SUCCESS;
		}
	}
	
	public InputStream getFileInputStream() {
		return fileInputStream;
	}
	
	public void setFileInputStream(InputStream fileInputStream) {
		this.fileInputStream = fileInputStream;
	}
	
	public String getElements() {
		return elements;
	}
	
	public void setElements(String elements) {
		this.elements = elements;
	}

}
