/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package managed_beans;

import entities.User;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.annotation.FacesConfig;
import javax.faces.view.ViewScoped;
import util.DB;



/**
 *
 * @author jelic
 */
@Named(value = "usersManagedBean")
@ViewScoped
@FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class UsersManagedBean  implements Serializable{

    /**
     * Creates a new instance of UsersManagedBean
     */
    public UsersManagedBean() {
    }
    
    private List<User> allUsers;

    public List<User> getAllUsers() {
        return allUsers;
    }

    public void setAllUsers(List<User> allUsers) {
        this.allUsers = allUsers;
    }
    
    @PostConstruct
    public void getAllUsersFromDB(){
        allUsers = new ArrayList<>();
        
        Connection conn = DB.getInstance().getConnection();
        try(Statement stm = conn.createStatement();) {
            
            ResultSet rs = stm.executeQuery("select * from users");
            while(rs.next()){
                User user = new User();
                user.setUsername(rs.getString("username"));
                user.setFirstname(rs.getString("firstname"));
                user.setLastname(rs.getString("lastname"));
                
                allUsers.add(user);
            }
        } catch (SQLException ex) {
            Logger.getLogger(UsersManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            util.DB.getInstance().putConnection(conn);
        }
    }

    public void saveData(User user){
        user.setEdit(false);
    }
    
    public void delete(User user){
        allUsers.remove(user);
    }
    
}
