// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package test;

import java.sql.*;
import java.util.*;

public class WebworkUsers {
    private static WebworkUsers instance = null;
    private Connection con;
    private PreparedStatement selpw;
    private PreparedStatement insone;
    private PreparedStatement selall;
    private WebworkUsers() throws ClassNotFoundException,SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost/Test", "", "");
        selpw = con.prepareStatement("SELECT password FROM webwork_users WHERE username=?");
        insone = con.prepareStatement("INSERT INTO webwork_users VALUES (?,?,?)");
        selall = con.prepareStatement("SELECT username,fullname FROM webwork_users");
    }
    public synchronized static WebworkUsers getInstance() throws ClassNotFoundException,SQLException {
        if(instance == null) {
            instance = new WebworkUsers();
        }
        return instance;
    }
    public synchronized String getPassword(String username) throws SQLException {
        selpw.setString(1,username);
        ResultSet rs = selpw.executeQuery();
        return (rs.next() ? rs.getString(1) : null);
    }
    public synchronized void addUser(String username, String password, String fullname) throws SQLException {
        insone.setString(1, username);
        insone.setString(2, password);
        insone.setString(3, fullname);
        insone.executeUpdate();
    }
    public synchronized List getAll() throws SQLException {
        List res = new ArrayList();
        ResultSet rs = selall.executeQuery();
        while(rs.next()) {
            res.add(new User(rs.getString(2),rs.getString(1)));
        }
        return res;
    }
}
