/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DatabaseProvider;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Locale;
import java.util.Vector;
import models.Message;
import models.User;

/**
 *
 * @author Li GUo
 */
public class AuthenticationProvider extends BaseDbProvider {

    public User registerUser(User user) throws Exception {
        try {            
            connect();
            String sql = String.format("CALL register_user('%s', '%s', '%s');", user.getUserName(), user.getEmail(), user.getPassword());                        
            statement = connection.createStatement();            
            ResultSet resultSet = statement.executeQuery(sql);            
            if(resultSet.first()) {
                user.setId(resultSet.getInt("Id"));
                
            } else {
                user = null;
            }            
            disconnect();
            return user;
        } catch (Exception e) {
            throw new Exception("error occured while saving the user data!");
        }
    }
    
    public User getUser(User user) throws Exception {
        try {
            connect();            
            String sql = String.format("CALL get_user('%s', '%s', '%s');", user.getEmail(), user.getUserName(), user.getPassword());
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            if(resultSet.first()) {
                user.setId(resultSet.getInt("Id"));
                user.setEmail(resultSet.getString("Email"));
                user.setUserName(resultSet.getString("UserName"));
                user.setPassword("");
            } else {
                user = null;
            }
            disconnect();
            return user;
        } catch (Exception e) {
            throw new Exception("error occured while getting the user data!");
        }        
    }
    
    public User getUserWithUsername(User newUser) throws Exception {
        try {
            connect();            
            String sql = String.format("SELECT * FROM Users WHERE UserName='%s'", newUser.getUserName());
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            User user = new User();
            if(resultSet.first()) {
                user.setId(resultSet.getInt("Id"));
                user.setEmail(resultSet.getString("Email"));
                user.setUserName(resultSet.getString("UserName"));
                user.setPassword("");
            } else {
                user = null;
            }
            disconnect();
            return user;
        } catch (Exception e) {
            throw new Exception("error occured while getting the user data!");
        }        
    }
}