package com.izouma.nineth.utils;


import com.anji.captcha.util.StringUtils;
import com.izouma.nineth.domain.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
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 java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * Created by IDEA
 * User: mashaohua
 * Date: 2016-10-19 10:21
 * Desc:
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    private static Environment env;

    private static boolean runDev;

    private static boolean runTest;

    private static boolean runProd;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextUtil.context = context;
        //初始化记录应用环境
        ApplicationContextUtil.env = context.getBean(Environment.class);
        List<String> envList = Arrays.asList(env.getActiveProfiles());
        if(envList.contains("dev")){
            runDev = true;
        }
        if(envList.contains("test")){
            runTest = true;
        }
        if(envList.contains("prod")){
            runProd = true;
        }

    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    public static boolean isRunDev() {
        return runDev;
    }

    public static boolean isRunTest() {
        return runTest;
    }

    public static boolean isRunProd() {
        return runProd;
    }

    /**
     * 最高级别管理员
     * @return
     */
    public static boolean isHighestAdmin(User user){
        String highestAdmin = env.getProperty("highestAdmin");
        if(StringUtils.isBlank(highestAdmin)){
            return false;
        }

        List<String> authedUsers = Arrays.asList(highestAdmin.split(","));
        if(user != null && authedUsers.contains(user.getUsername())){
            return true;
        }

        return false;
    }


    /**
     * 获得当前web请求对象
     * @return
     */
    public static HttpServletRequest currentRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            return request;
        }
        return null;
    }



}
