package sk.vrto.service.domain;
import sk.vrto.domain.Contact;
import sk.vrto.domain.User;
/**
* Smartly creates new contact from given email address.
*/
public class ContactCreator {
/**
* Tries to figure out a contact name from the given address and encapsulates that in Contact class.
* <br /><b>Examples:</b>
* <ul>
* <li>chuck.norris@gmail.com will return {@code Chuck Norris}</li>
* <li>miso@google.sk will return {@code Miso}</li>
* <li>bad.ass.modofoko@whatever.fi will return {@code Bad Ass.modofoko}</li>
* </ul>
* @param emailAddress Address to inspect
* @param user Logged user
* @return New contact
*/
public Contact mapFromAddress(String emailAddress, User user) {
// get two parts: name @ host.domain
String[] atSplit = emailAddress.split("@");
if (1 >= atSplit.length) {
throw new IllegalArgumentException(
"Cannot parse e-mail address, missing '@' :" + emailAddress);
}
String name;
String surname;
// is there dot in name? like chuck.norris
String[] dotSplit = atSplit[0].split("\\.");
if (1 < dotSplit.length) {
name = namify(dotSplit[0]);
surname = namify(dotSplit[1]);
} else {
name = namify(atSplit[0]);
surname = "";
}
return new Contact(surname.isEmpty() ? name : name + " " + surname,
emailAddress, user);
}
private String namify(String val) {
return val.substring(0, 1).toUpperCase() + val.substring(1, val.length());
}
}