package motoSample;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;

import java.util.logging.Logger;
import javax.inject.Inject;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import javax.faces.model.SelectItem;

import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFactory;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;

@ManagedBean
@SessionScoped
public class UserBean implements Serializable {

    @Inject
    private Logger log;

    @Inject
    private FacesContext context;

    @ManagedProperty("#{loginMemberBean}")
    private LoginMemberBean loginMemberBean;

    public void setLoginMemberBean(LoginMemberBean loginMemberBean) {
        this.loginMemberBean = loginMemberBean;
    }

    private String uid;
    private String pwd;
    private String uname;
    
    private ArrayList<SelectItem> flights;
    
    private boolean login = false;

    public boolean isLoggedIn() {
        return login;
    }
    
    public String getUid() {
        return uid;
    }
    public String getPwd() {
        return pwd;
    }
    public String getUname() {
        return uname;
    }
    public void setUid(String uid) {
        this.uid = uid;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    
    public ArrayList<SelectItem> getFlights() {
        return flights;
    }
    
    private void initUserFlights(Connection conn) {
        if (flights == null) {
            flights = new ArrayList<SelectItem>();
        }
        flights.clear();
        
        try {
            String sqlString = "select flight_name from tb_user_flights where user_id=\'" + uid +"\'";
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sqlString);
            while(rs.next()) {
                String ft = rs.getString("flight_name");
                flights.add(new SelectItem(ft, ft));
            }
            statement.close();
        }
        catch (SQLException se) {
            log.severe("sql flight err!!!");
        }
    }

    private void initLogin(Connection conn, String user_name) {
        login = true;
        this.uname = user_name;
        initUserFlights(conn);

        //add to the app login list.
        loginMemberBean.login(uid, true);
        //notify log in message
        for (SelectItem si : flights) {
            String chatRoom = si.getValue().toString();
            
            PushMsg pm = PushMsg.newLoginPushMsg();
            PushMsg.LoginUser lu = pm.getLoginUser();
            lu.setUid(uid);
            lu.setLogin(true);

            String br_url = "/comet/" + chatRoom;
            Broadcaster b = BroadcasterFactory.getDefault().lookup(br_url, true);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String json = mapper.writeValueAsString(pm);
                b.broadcast(json);
            } catch (IOException e) {
                log.severe("json encode error.");
            }
        }
    }

    public String doLogin() {

        try {
            Connection conn = Resources.getConnection();
            
            String sqlString = "select user_password, user_name from tb_users where user_id=\'" + uid +"\'";

            Statement statement = conn.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.

            ResultSet rs = statement.executeQuery(sqlString);
            if(rs.next())
            {
                // read the result set
                String db_pwd = rs.getString("user_password");
                //log.info("pwd = " + db_pwd);
                //log.info("name = " + rs.getString("user_name"));

                if (pwd.equals(db_pwd)) {
                    initLogin(conn, rs.getString("user_name"));

                    statement.close();
                    conn.close();

                    ///after login, redirect to the user specified url.
                    HttpSession session = Resources.getSession();
                    String request_url = (String) session.getAttribute("request_url");
                    if (request_url == null)
                        request_url = "secured/chat.jsf";
                    return request_url + "?faces-redirect=true";
                }

            }
            else {
                log.info("uid " + uid + "not found...");
            }
            
            statement.close();
            conn.close();
        }
        catch (SQLException se) {
            log.severe("sql err!!!");
        }
        /*
        */
        
        return "";
    }
    

    public String doOpenIdLogin (String openid, HttpSession session) {

        try {
            Connection conn = Resources.getConnection();
            
            String sqlString = "select user_id, user_name from tb_users where use_open_id=\'TRUE\' and user_open_id=\'" + openid +"\'";

            Statement statement = conn.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.

            ResultSet rs = statement.executeQuery(sqlString);
            if(rs.next())
            {
                this.uid = rs.getString("user_id");
                initLogin(conn, rs.getString("user_name"));
                statement.close();
                conn.close();

                ///after login, redirect to the user specified url.
                String request_url = (String) session.getAttribute("request_url");
                if (request_url == null)
                    request_url = "/secured/chat.jsf";
                return request_url + "?faces-redirect=true";
            }
            else {
                log.info("openid " + openid + " not found...");
            }
            statement.close();
            conn.close();
        }
        catch (SQLException se) {
            log.severe("sql err!!!");
        }
        return null;
    }

    public String doLogout() {
        //notify log in message
        for (SelectItem si : flights) {
            String chatRoom = si.getValue().toString();
            PushMsg pm = PushMsg.newLoginPushMsg();
            PushMsg.LoginUser lu = pm.getLoginUser();
            lu.setUid(uid);
            lu.setLogin(false);

            String br_url = "/comet/" + chatRoom;
            Broadcaster b = BroadcasterFactory.getDefault().lookup(br_url, true);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String json = mapper.writeValueAsString(pm);
                b.broadcast(json);
            } catch (IOException e) {
                log.severe("json encode error.");
            }
        }
        loginMemberBean.login(uid, false);
        context.getExternalContext().invalidateSession();
        //login = false;
        return "/login.jsf";
    }
    
}
