package cactusServer.models;
import javax.inject.Singleton;
import cactusServer.entities.*;
import java.net.URI;
import java.util.*;
@Singleton
public class Accounts {
private static Accounts theInstance = null;
private ArrayList<Account> accounts = new ArrayList<>();
private HashSet<String> idSet = new HashSet<>();
private Session session;
private Accounts() {
}
public static Accounts getInstance() {
if (theInstance == null) {
theInstance = new Accounts();
}
return theInstance;
}
public Session createAcount(String userID, String userName, String userPass) {
String uniqueID = RandomStringGenerator.createUniqueString(64, RandomStringGenerator.ALPHA_NUMERIC, idSet);
idSet.add(uniqueID);
Account newAccount = new Account(userID, userName, userPass);
newAccount.setUniqueID(uniqueID);
accounts.add(newAccount);
newAccount.formToken();
session = new Session(newAccount, URI.create(uniqueID));
return session;
}
public Account getAccount(String token) {
Account editAccount;
for (int i = 0; i < accounts.size(); i++) {
editAccount = accounts.get(i);
if (editAccount.getToken().equals(token)) {
return editAccount;
}
}
return null;
}
public Account getAccountByID(String userID) {
Account editAccount;
for (int i = 0; i < accounts.size(); i++) {
editAccount = accounts.get(i);
if (editAccount.getId().equals(userID)) {
return editAccount;
}
}
return null;
}
public Account getAccountByName(String userName) {
Account editAccount;
for (int i = 0; i < accounts.size(); i++) {
editAccount = accounts.get(i);
if (editAccount.getName().equals(userName)) {
return editAccount;
}
}
return null;
}
public Session loginAccount(String userID, String userPass) {
if (idSet.contains(userID) && getAccountByID(userID).getPass().equals(userPass)) {
Accounts.getInstance().getAccountByID(userID).setLogin(true);
session = new Session(Accounts.getInstance().getAccountByID(userID), URI.create(idSet.toString()));
return session;
} else {
return null;
}
}
public String logoutAccount(String token) {
Accounts.getInstance().getAccount(token).setLogin(false);
return "";
}
}