package org.smartframework.common.utils;


import com.alibaba.fastjson.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartframework.common.DataObject;
import org.smartframework.common.GlobalConfig;

public class ExRequestUtils {
    protected static final Logger log = LoggerFactory.getLogger(ExRequestUtils.class);

    public ExRequestUtils() {
    }

    public static String decodeURL(Object value) {
        if(value == null) {
            throw new IllegalArgumentException("Null object parameter");
        } else {
            try {
                return URLDecoder.decode(value.toString(), "UTF-8");
            } catch (UnsupportedEncodingException var2) {
                throw new RuntimeException(var2);
            }
        }
    }

    public static boolean hasSession(HttpServletRequest request) {
        return request.getSession(false) != null;
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null && name != null && name.length() != 0) {
            Cookie[] var3 = cookies;
            int var4 = cookies.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Cookie cookie = var3[var5];
                if(cookie.getName().equals(name)) {
                    return cookie;
                }
            }

            return null;
        } else {
            return null;
        }
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie != null?cookie.getValue():null;
    }

    public static String removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {
        return removeCookie(request, response, name, "/");
    }

    public static String removeCookie(HttpServletRequest request, HttpServletResponse response, String name, String path) {
        Cookie cookie = getCookie(request, name);
        if(cookie != null) {
            cookie.setValue((String)null);
            cookie.setMaxAge(0);
            cookie.setPath(path);
        }

        setCookie(request, response, cookie);
        return null;
    }

    public static void setCookie(HttpServletRequest request, HttpServletResponse response, Cookie cookie) {
        if(cookie != null) {
            cookie.setSecure(request.isSecure());
            response.addCookie(cookie);
        }

    }

    public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge, String path) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setPath(path);
        cookie.setSecure(request.isSecure());
        response.addCookie(cookie);
    }

    public static String getLoginToken(HttpServletRequest request) {
        String name = GlobalConfig.getConfigValue("filter.cookie.loginToken");
        if(ExStringUtils.isBlank(name)) {
            name = "LTJ_WEBOA_LOGIN_TOKEN";
        }

        String loginToken = getCookieValue(request, name);
        if(loginToken == null) {
            loginToken = request.getParameter("token");
        }

        return loginToken;
    }


    public static Map buildParametersMap(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String contentType = request.getContentType();
        String method = request.getMethod();
        DataObject paramMap = new DataObject();
        if("application/json".equalsIgnoreCase(contentType) && "Post".equalsIgnoreCase(method)) {
            String queryParams = IOUtils.toString(request.getInputStream(), "UTF-8");
            if(queryParams == null || queryParams.length() == 0) {
                JSONObject jsonParams = new JSONObject();
                Enumeration names = request.getParameterNames();

                while(names.hasMoreElements()) {
                    String paramName = (String)names.nextElement();
                    if(!"v,time,nonce,token".contains(paramName)) {
                        if(request.getParameter(paramName) != null) {
                            jsonParams.put(paramName, request.getParameter(paramName));
                        } else {
                            jsonParams.put(paramName, ExStringUtils.concat(request.getParameterValues(paramName)));
                        }
                    }
                }

                queryParams = jsonParams.toJSONString();
            }

            Map tmpMap = ExStringUtils.parseJsonParameters(queryParams);
            if(tmpMap == null) {
                tmpMap = ExStringUtils.parseUrlParameters(queryParams);
            }

            paramMap.putAll(tmpMap);
        } else {
            Enumeration names = request.getParameterNames();

            while(names.hasMoreElements()) {
                String name = (String)names.nextElement();
                String value = request.getParameter(name);
                paramMap.put(name, value);
            }
        }
        return paramMap;
    }

    public static Map buildMultipartContentMap(HttpServletRequest request) throws IOException {
        Map paramMap = new HashMap();
        if(ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
            servletFileUpload.setHeaderEncoding("UTF-8");

            try {
                FileItemIterator items = servletFileUpload.getItemIterator(request);

                String name;
                while(items.hasNext()) {
                    FileItemStream item = items.next();
                    name = item.getFieldName();
                    byte[] content = toByteArray(item.openStream());
                    if(item.isFormField()) {
                        paramMap.put(name, new String(content, "UTF-8"));
                    } else {
                        String fileName = item.getName();
                        paramMap.put(name + "-fileName", fileName);
                        paramMap.put(name + "-fileContent", content);
                        paramMap.put("isMultipartRequest", Boolean.valueOf(true));
                    }
                }

                Enumeration names = request.getParameterNames();

                while(names.hasMoreElements()) {
                    name = (String)names.nextElement();
                    paramMap.put(name, request.getParameter(name));
                }
            } catch (FileUploadException var9) {
                log.error("buildMultipartContentMap",var9);
            } catch (IOException var10) {
                log.error("buildMultipartContentMap",var10);
            }
        }

        return paramMap;
    }

    public static String getUserIP(HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        return remoteHost;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        int BUFFER_SIZE = 4096;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[BUFFER_SIZE];
        boolean var4 = false;

        int len;
        while((len = input.read(b, 0, BUFFER_SIZE)) != -1) {
            baos.write(b, 0, len);
        }

        baos.flush();
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    public static int getPageIndex(Map paramMap) {
        int pageIndex = 1;
        if(paramMap.get("pageIndex") != null) {
            pageIndex = ExStringUtils.parseInt((String)paramMap.get("pageIndex"), 1);
        } else if(paramMap.get("page") != null) {
            pageIndex = ExStringUtils.parseInt((String)paramMap.get("page"), 1);
        }

        return pageIndex;
    }

    public static int getPageSize(Map paramMap) {
        int pageSize = 100;
        if(paramMap.get("pageSize") != null) {
            pageSize = ExStringUtils.parseInt((String)paramMap.get("pageSize"), 20);
        } else if(paramMap.get("rows") != null) {
            pageSize = ExStringUtils.parseInt((String)paramMap.get("rows"), 20);
        }

        return pageSize;
    }



}