package cn.quantgroup.xyqb.controller;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSession;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSessionFromRedis;

/**
 * Created by Miraculous on 15/7/5.
 */
public interface IBaseController {

    @Deprecated
    default User getCurrentUser() {
        SessionStruct session = getXSession();
        if (session == null) {
            return null;
        }
        return getXSession().getValues().getUser();
    }

    @Deprecated
    default SessionStruct getSessionStruct() {
        return getXSession();
    }

    default User getCurrentUserFromRedis() {
        SessionStruct session = getXSessionFromRedis();
        if (session == null) {
            return null;
        }
        return session.getValues().getUser();
    }

    default SessionStruct getCurrentSessionFromRedis() {
        return getXSessionFromRedis();
    }


    default HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return attrs.getRequest();
    }

    default String getIp() {
        HttpServletRequest request = getRequest();
        return IpUtil.getRemoteIP(request);
    }

    default String getProtocol() {
        return StringUtils.startsWith(getRequest().getHeader("x-forwarded-proto"), "https") ? "https:" : "http:";
    }

    default Map<String, String> getRequestHeaderMap(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        HashMap<String, String> map = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            if (Objects.equals("authorization", key)) {
                continue;
            }
            map.put(key, request.getHeader(key));
        }
        return map;
    }
}
