package com.wisedu.coeus.helper;

import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.ServletContext;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ApplicationHelper implements ApplicationContextAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationHelper.class);

    private static String webRootPath;
    private static final Object webRootPathLock = new Object();
    private static ServletContext servletContext;
    private static ApplicationContext appContext;
    private static String contextPath;
    public static String LOCAL_IP = "";

    static {
        try {
            LOCAL_IP = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appContext = applicationContext;
    }

    /**
     * 获取当前Web的根目录
     *
     * @return
     */
    public static String getWebRootPath() {
        if (webRootPath != null) {
            return webRootPath;
        }
        synchronized (webRootPathLock) {
            // double check.
            if (webRootPath != null) {
                return webRootPath;
            }

            String path = servletContext.getRealPath("/");

            path = path.replace('\\', '/');


            if (path.charAt(path.length() - 1) == '/') {
                path = path.substring(0, path.length() - 1);
            }

            webRootPath = path;

            LOGGER.debug("Get web root path: [{}].", webRootPath);
        }

        return webRootPath;
    }

    public static Object getBean(String name) {
        Object obj = null;
        try {
            obj = appContext.getBean(name);
        } catch (Exception e) {
            obj = null;
        }
        return obj;
    }

    /**
     * 获取Servlet上下文
     *
     * @return
     */
    public static ServletContext getServletContext() {
        return servletContext;
    }

    public static void setServletContext(ServletContext sc) {
        servletContext = sc;
    }

    public static String getContextPath() {
        if (contextPath != null) {
            return contextPath;
        }

        contextPath = servletContext.getContextPath();

        return contextPath;
    }


}
