package controllers;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.net.URLCodec;

import play.mvc.After;
import play.mvc.Before;
import play.mvc.Controller;

/**
 * ExcelFormat extends PlayFramework Sessoin.format according to http accept header
 * 
 * @author luog
 *
 */
public class ExcelFormat extends Controller {
    @Before
    public static void extendFormat() {
        if (request.headers.get("accept") != null) {
            String accept = request.headers.get("accept").value();
            if (accept.indexOf("text/csv") != -1) request.format = "csv";
            if (accept.matches(".*application\\/(excel|vnd\\.ms\\-excel|x\\-excel|x\\-msexcel).*")) request.format = "xls";
            if (accept.indexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") != -1) request.format = "xlsx";
        }
    }
    
    private static final URLCodec encoder = new URLCodec();
    @After
    public static void setHeader() throws UnsupportedEncodingException {
        if (null != request.format && !request.format.matches("(csv|xls|xlsx)")) return;
        
        if (!response.headers.containsKey("Content-Disposition")) {
            String fileName = renderArgs.get("fileName", String.class);
            if (fileName == null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=export." + request.format);
            } else {
                response.setHeader(
                        "Content-Disposition",
                        "attachment; filename="
                                + encoder.encode(fileName, "utf-8"));
            }
            
            if (request.format.equals("xls")) {
                response.setContentTypeIfNotSet("application/vnd.ms-excel");
            } else if (request.format.equals("xlsx")) {
                response.setContentTypeIfNotSet("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            } else if (request.format.equals("csv")) {
                response.setContentTypeIfNotSet("text/csv");
            }
        }
    }
}
