package voxo.server.actions;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.ArrayList;
import voxo.common.entities.Contact;
import voxo.common.entities.User;
import voxo.common.enums.EnumPacket;
import voxo.common.packets.ClientRequestPacket;
import voxo.server.Messages;
import voxo.server.exceptions.RequestException;
import voxo.server.managers.ContactManager;
import voxo.server.managers.UserManager;
public class ContactAddAction {
public ContactAddAction(InetAddress ip, ClientRequestPacket o) throws UnknownHostException, IOException, SQLException, RequestException {
// Get the clients affected
User u = UserManager.searchUserAbsolute(new User(null, o.getUsername(), null, null, null, null, null)).get(0);
User cu = UserManager.searchUserAbsolute(new User(null, o.getContactName(), null, null, null, null, null)).get(0);
if (cu == null) {
throw new RequestException(Messages.getString("ContactAddAction.ERR_ContactNotFound")); //$NON-NLS-1$
}
if (u == null) {
throw new RequestException(Messages.getString("ContactAddAction.ERR_UserNotFound")); //$NON-NLS-1$
}
// Check for existing contact
Contact c = new Contact(null, u.getUserId(), cu.getUserId(), null);
ArrayList<Contact> alc = ContactManager.searchContactAbsolute(c);
if (alc.size() > 0) {
new SendMessageAction(Messages.getString("ContactAddAction.AlreadySent"), u, EnumPacket.SERVER_Error); //$NON-NLS-1$
throw new RequestException(Messages.getString("ContactAddAction.ERR_AlreadyContact")); //$NON-NLS-1$
}
// Add contact
ContactManager.addContact(new Contact(null, u.getUserId(), cu.getUserId(), false));
// Notify users
new SendMessageAction(String.format(Messages.getString("ContactAddAction.ResponseTarget"), u.getUsername()), cu, EnumPacket.SERVER_Notice); //$NON-NLS-1$
if(cu.getOnline() == true) {
new SendContactListAction(cu);
new SendMessageAction(String.format(Messages.getString("ContactAddAction.ResponseSelf"), cu.getUsername()), u, EnumPacket.SERVER_Notice); //$NON-NLS-1$
}
}
}