package cn.keking.web.filter;

import cn.keking.config.ConfigConstants;
import cn.keking.config.SpringContextConfig;
import cn.keking.config.WatermarkConfigConstants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author chenjh
 * @since 2020/5/13 18:34
 */
public class AttributeSetFilter implements Filter {

    private  ConfigConstants configConstants;
    private WatermarkConfigConstants watermarkConfigConstants;

    public AttributeSetFilter(ConfigConstants configConstants,WatermarkConfigConstants watermarkConfigConstants){
        this.configConstants = configConstants;
        this.watermarkConfigConstants = watermarkConfigConstants;
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        this.setWatermarkAttribute(request);
        this.setFileAttribute(request);
        filterChain.doFilter(request, response);
    }

    /**
     * 设置办公文具预览逻辑需要的属性
     * @param request request
     */
    private void setFileAttribute(ServletRequest request){
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        request.setAttribute("pdfDownloadDisable", configConstants.getPdfDownloadDisable());
        request.setAttribute("fileKey", httpRequest.getParameter("fileKey"));
        request.setAttribute("switchDisabled", configConstants.getOfficePreviewSwitchDisabled());
        request.setAttribute("fileUploadDisable", configConstants.getFileUploadDisable());
    }

    /**
     * 设置水印属性
     * @param request request
     */
    private void setWatermarkAttribute(ServletRequest request) {
        String watermarkTxt = request.getParameter("watermarkTxt");
        request.setAttribute("watermarkTxt", watermarkTxt != null ? watermarkTxt : watermarkConfigConstants.getWatermarkTxt());
        request.setAttribute("watermarkXSpace", watermarkConfigConstants.getWatermarkXSpace());
        request.setAttribute("watermarkYSpace", watermarkConfigConstants.getWatermarkYSpace());
        request.setAttribute("watermarkFont", watermarkConfigConstants.getWatermarkFont());
        request.setAttribute("watermarkFontsize", watermarkConfigConstants.getWatermarkFontsize());
        request.setAttribute("watermarkColor", watermarkConfigConstants.getWatermarkColor());
        request.setAttribute("watermarkAlpha", watermarkConfigConstants.getWatermarkAlpha());
        request.setAttribute("watermarkWidth", watermarkConfigConstants.getWatermarkWidth());
        request.setAttribute("watermarkHeight", watermarkConfigConstants.getWatermarkHeight());
        request.setAttribute("watermarkAngle", watermarkConfigConstants.getWatermarkAngle());
    }

    @Override
    public void destroy() {

    }
}
