package com.goafanti.core.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;

import com.goafanti.common.bo.Result;
import com.goafanti.common.utils.LoggerUtils;

public class ShiroFilterUtils {
	final static Class<? extends ShiroFilterUtils> CLAZZ = ShiroFilterUtils.class;

	@Value(value = "${app.name}")
	private String appName;

	/**
	 * 是否是Ajax请求
	 * 
	 * @param request
	 * @return
	 */
	public boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("accept") != null && request.getHeader("accept").indexOf("application/json") > -1)
				|| (request.getHeader("X-Requested-With") != null
						&& request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)
				|| isFromAPP(request);
	}

	/**
	 * 
	 * @param request
	 * @return true if App request
	 */
	public boolean isFromAPP(HttpServletRequest request) {
		return request.getHeader("User-Agent") != null && request.getHeader("User-Agent").indexOf(appName) > -1;
	}

	/**
	 * response 输出JSON
	 * 
	 * @param hresponse
	 * @param resultMap
	 * @throws IOException
	 */
	public void out(HttpServletResponse response, Result res) {
		PrintWriter out = null;
		try {
			response.setHeader("Content-Type", "application/json");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.println(JSON.toJSONString(res));
		} catch (Exception e) {
			LoggerUtils.fmtError(CLAZZ, e, "输出JSON报错。");
		} finally {
			if (null != out) {
				out.flush();
				out.close();
			}
		}
	}

	public void setAppName(String appName) {
		this.appName = appName;
	}
}
