package com.ejie.aa94a.view;

import java.util.Locale;
import java.util.Map;

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

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.LocalizedResourceHelper;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractView;

import com.ejie.aa94a.constantes.Constantes;

public abstract class BobinasAbstractExcelView extends AbstractView {
	private String url;

	public BobinasAbstractExcelView() {
		setContentType(Constantes.CONTENT_TYPE_XLSX);
	}

	public void setUrl(String url) {
		this.url = url;
	}

	protected boolean generatesDownloadContent() {
		return true;
	}

	protected final void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		XSSFWorkbook workbook;
		if (this.url != null) {
			workbook = getTemplateSource(this.url, request);
		} else {
			workbook = new XSSFWorkbook();
			this.logger.debug("Created Excel Workbook from scratch");
		}

		buildExcelDocument(model, workbook, request, response);

		response.setContentType(getContentType());

		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		out.flush();
	}

	protected XSSFWorkbook getTemplateSource(String url,
			HttpServletRequest request) throws Exception {
		LocalizedResourceHelper helper = new LocalizedResourceHelper(
				getApplicationContext());
		Locale userLocale = RequestContextUtils.getLocale(request);
		Resource inputFile = helper.findLocalizedResource(url,
				Constantes.EXTENSION_XLSX, userLocale);

		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Loading Excel workbook from " + inputFile);
		}
		// POIFSFileSystem fs = new POIFSFileSystem(inputFile.getInputStream());
		return new XSSFWorkbook(inputFile.getInputStream());
	}

	protected abstract void buildExcelDocument(Map<String, Object> paramMap,
			XSSFWorkbook paramXSSFWorkbook,
			HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse) throws Exception;

	// protected HSSFCell getCell(HSSFSheet sheet, int row, int col) {
	// HSSFRow sheetRow = sheet.getRow(row);
	// if (sheetRow == null) {
	// sheetRow = sheet.createRow(row);
	// }
	// HSSFCell cell = sheetRow.getCell((short) col);
	// if (cell == null) {
	// cell = sheetRow.createCell((short) col);
	// }
	// return cell;
	// }
	//
	// protected void setText(HSSFCell cell, String text) {
	// cell.setCellType(1);
	// cell.setCellValue(text);
	// }
}
