package motoSample;

import javax.inject.Inject;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


import javax.faces.context.FacesContext;
import javax.faces.context.ExternalContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class Resources {

    private static Logger log = Logger.getLogger(Resources.class.getName());


    //injection producer....
    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    public static Connection getConnection() {
        try {
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:jboss/datasource/moto-web-app-ds");
            Connection conn = ds.getConnection();
            return conn;
        }
        catch (NamingException ne) {
            log.severe("context not found!!!");
        }
        catch (SQLException se) {
            log.severe("sql get connection err!!!");
        }
        return null;
    }


    public static HttpSession getSession() {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext exContext = context.getExternalContext();
        HttpServletRequest req = (HttpServletRequest) exContext.getRequest();
        HttpSession session = req.getSession();
        return session;
    }
}
