Newer
Older
CactusServer / src / main / java / cactusServer / models / Accounts.java
package cactusServer.models;

import javax.inject.Singleton;

import cactusServer.entities.*;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;

@Singleton
public class Accounts {
	private static Accounts theInstance = null;
	private ArrayList<Account> accounts = new ArrayList<>();
	private HashSet<String> idSet = new HashSet<String>();
	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) {
		if (!idSet.add(userID)) {
			return null;
		}
		Account newAccount = new Account(userID,userName, userPass);
		accounts.add(newAccount);
		newAccount.formToken();
		session = new Session(newAccount,URI.create(RandomStringGenerator.createUniqueString(64, RandomStringGenerator.ALPHA_NUMERIC, idSet)));

		return session;
	}

	public Account updateAccount(String userID, String userName, String userPass) {
		if (idSet.contains(userID)) {
			Accounts.getInstance().getAccount(userID).setName(userName);
			Accounts.getInstance().getAccount(userID).setPass(userPass);
			return Accounts.getInstance().getAccount(userID);
		} else {
			return null;
		}
	}

	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 Session loginAccount(String userID, String userPass) {
		if (idSet.contains(userID) && getAccount(userID).getPass().equals(userPass)) {
			Accounts.getInstance().getAccount(userID).setLogin(true);
			return session;
		} else {
			return null;
		}
	}

	public String logoutAccount(String token) {
		return "";
	}

	public String deleteAccount(String userID) {
		if (idSet.contains(userID)) {
			accounts.remove(userID);
			idSet.remove(userID);
			return "complated remove account";
		} else {
			return "not exist";
		}
	}

}