/* c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil
 * vi: set shiftwidth=2 tabstop=2 expandtab:
 * :indentSize=2:tabSize=2:noTabs=true:
 */

package beans;

import common.*;
import db.*;

import javax.faces.bean.*;
import javax.inject.Inject;
import javax.persistence.*;


@ManagedBean
@SessionScoped
public class
LoginBean {

  private String pw_hash;
  private String user_name;

  @Inject
  EntityManager em;

  private boolean is_logged_in = false;

  private UserTypeEnum user_type = UserTypeEnum.NONE;

/****************************************************************************/

  public void
  setPassword (String s) {
    this.pw_hash = Utils.hash_func(s);
  }

  public String
  getPassword () {
    return null;
  }

  public void
  setUserName (String s) {
    this.user_name = s;
  }

  public UserTypeEnum
  getUserType () {
    return this.user_type;
  }
/****************************************************************************/

  public String
  studentLogin () {
    if (this.is_logged_in) {
      return "success";
    }
    Student stnt = em.find(Student.class, this.user_name);
    if (stnt == null) {
      this.logout();
      return "falure";
    }
    if (stnt.getPwd() != this.pw_hash) {
      this.logout();
      return "falure";
    }
    this.user_type = UserTypeEnum.STUDENT;
    this.is_logged_in = true;
    this.pw_hash = null;
    return "success";
  }

  public String 
  staffLogin () {
    if (this.is_logged_in) {
      return "success";
    }
    Staff stf = em.find(Staff.class, this.user_name);
    if (stf == null) {
      this.logout();
      return "falure";
    }
    if (stf.getPwd() != this.pw_hash) {
      this.logout();
      return "falure";
    }
    this.user_type = UserTypeEnum.STAFF;
    this.is_logged_in = true;
    this.pw_hash = null;
    return "success";
  }

  public void
  logout () {
    this.user_name = null;
    this.user_type = UserTypeEnum.NONE;
    this.is_logged_in = false;
    this.pw_hash = null;
  }

}
