/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.web.view.document;

import java.io.IOException;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Workbook;
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;

public abstract class AbstractExcelView extends org.springframework.web.servlet.view.document.AbstractXlsxView {

	private String url;

	/**
	 * Set the URL of the Excel Workbook source, without localization part nor .xlsx extension.
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * Creates the Excel Workbook from an existing XLSX document.
	 *
	 * @param url
	 *            the URL of the Excel template without localization part nor extension
	 * @param request
	 *            current HTTP request
	 * @return the Workbook
	 *
	 * @throws IOException
	 *             in case of failure
	 */
	private Workbook getTemplateSource(String url, HttpServletRequest request) throws IOException {
		LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext());
		Locale userLocale = RequestContextUtils.getLocale(request);
		Resource inputFile = helper.findLocalizedResource(url, ".xlsx", userLocale);

		// Create the Excel Workbook from the source.
		if (logger.isDebugEnabled()) {
			logger.debug("Loading Excel workbook from " + inputFile);
		}
		return new XSSFWorkbook(inputFile.getInputStream());
	}

	/**
	 * This implementation creates an {@link XSSFWorkbook} for the XLSX format either from URL (if provided) or from scratch.
	 */
	@Override
	protected Workbook createWorkbook(Map<String, Object> model, HttpServletRequest request) {
		Workbook workbook;

		if (this.url != null) {
			try {
				workbook = getTemplateSource(this.url, request);
			} catch (IOException e) {
				logger.error("Failed to load Excel Workbook from URL!", e);
				workbook = new XSSFWorkbook();
			}
		} else {
			workbook = new XSSFWorkbook();
			logger.debug("Created Excel Workbook from scratch");
		}

		return workbook;
	}

}