package com.yvan.freemarker;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * freemarker 的静态资源函数
 * Created by luoyifan on 2017/3/28.
 */
@Component
public class StaticFunctions {

    @Value("${route.static_domain}")
    private String staticDomain;

    @Value("${route.static_version}")
    private String staticVersion;

    public static HttpServletRequest currentRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpServletResponse currentResponse() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 第三方前端库函数资源
     * 根据 jzt.static_domain 的配置，生成静态资源路径
     * <p/>
     * 比如 /css/base.css 会根据配置变成
     * http://static.yyjzt.com/js/jquery.js 或
     * /static/js/jquery.js
     */
    @FreemarkerFunction("s3")
    public String s3(String resourcePath) {
        return staticDomain + resourcePath;
    }

    /**
     * 自己编写的前端库资源
     * 根据 jzt.static_domain 的配置，生成静态资源路径
     * <p/>
     * 比如 /css/base.css 会根据配置变成
     * http://static.yyjzt.com/css/base.css?v=20170328 或
     * /static/css/base.css?v=20170328
     */
    @FreemarkerFunction("s0")
    public String s0(String resourcePath) {
        return staticDomain + resourcePath + "?v=" + staticVersion;
    }


    @FreemarkerFunction("req")
    public String req(String name) {
        try {
            return currentRequest().getParameterMap().get(name)[0];
        } catch (Exception e) {
            return "";
        }
    }

    @FreemarkerFunction("nowDate")
    public String nowDate() {
        return new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
    }

    @FreemarkerFunction("nowDateTime")
    public String nowDateTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    }

}
