package oving2;

import java.util.Date;
import com.google.common.net.InternetDomainName;

public class Person {
	private String name;
	private String email;
	private Date birthday;
	private char gender;
	private String SSN;

	public Person() {
	}

	public String getName() {
		return name;
	}

	public String getEmail() {
		return email;
	}

	public Date getBirthday() {
		return birthday;
	}

	public char getGender() {
		return gender;
	}

	public String getSSN() {
	    return SSN;
	}

	public void setName(String name) {
		int i = name.indexOf(' ');
		if (i == -1) {
			throw new IllegalArgumentException("Did not find both prename and surname.");
		}
		String prename = name.substring(0, i);
		String surname = name.substring(i + 1, name.length());
		if (prename.contains(" ") || surname.contains(" ")) {
			throw new IllegalArgumentException("There should only be one space which separates prename and surname.");
		}
		if (prename.length() < 2 || surname.length() < 2) {
			throw new IllegalArgumentException("Prename or surname should not be less than 2 characters.");
		}
		if (!isAlphabetic(prename) || !isAlphabetic(surname)) {
			throw new IllegalArgumentException("Prename and surname should only contain letters.");
		}
		this.name = name;
	}

	private boolean isAlphabetic(String s) {
		char[] chars = name.toCharArray();
		for (char c : chars) {
			if (!Character.isLetter(c)) {
				return false;
			}
		}
		return true;
	}

	public void setEmail(String email) {
		if (email != null) {
			throw new IllegalArgumentException("Email is already set.");
		}
		if (name == null) {
			throw new IllegalArgumentException("Name needs to be set before email.");
		}
		int i = email.indexOf('@');
		if (i == -1) {
			throw new IllegalArgumentException("Email should contain 1 @");
		}
		String[] names = name.split(" ");
		String first = email.substring(0, i);
		String second = email.substring(i + 1, email.length());
		if (first.contains("@") || second.contains("@")) {
			throw new IllegalArgumentException("Email should contain 1 @");
		}
		if (first != names[0] + "." + names[1]) {
			throw new IllegalArgumentException("Email username should be on the form: \"prename.surname\".");
		}

		boolean isDomain = true;
		try {
		    InternetDomainName d = InternetDomainName.from(second);
		    isDomain = d.hasPublicSuffix();
		} catch (IllegalArgumentException e) {
		    isDomain = false;
		}

		if (!isDomain) {
		    throw new IllegalArgumentException("Email domain is not on the form: \"local.domain\"");
		}

		this.email = email;
	}

	void setBirthday(Date date) {
	    Date now = new Date();
	    if (now.before(date)) {
		    throw new IllegalArgumentException("Birthday cannot be set to a future date.");
	    }
	    birthday = date;
	}

	void setGender(char c) {
	    if (c != 'M' && c != 'F' && c != '\0') {
		    throw new IllegalArgumentException("Invalid gender value.");
	    }
	    gender = c;
	}

	void setSSN(String s) {
	}
}

