package Assignment2;

import java.io.IOException;
import java.lang.IllegalStateException;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Formatter;

public class PlotMyAddress { 
	public static void main(String... args) {
		Person person = new Person();
		Address address = new Address();
		Scanner input = null;
		Formatter output = null;
		String[] records = null;
		String[] names = null;					
		String[] streetInfo = null;
		String[] cityProv = null;
		String nextLine;

		try {
			input = new Scanner(Paths.get("C:\\CST8284\\Input\\InputAddresses.txt"));
			output = new Formatter("C:\\CST8284\\output\\OutputAddresses.csv");

			while(input.hasNext()) {
				nextLine = input.nextLine();

				while (nextLine != null) {
					records = new String[4];

					for (int i = 0; i< 4; i++) {
						records[i] = nextLine;
						if (input.hasNext()) 
						{
							nextLine=input.nextLine();
						}						
					}

					names = records[0].split("\\s*(\\s|,)\\s*");					
					streetInfo = records[1].split("\\s+");
					cityProv = records[2].split("\\s*(\\s|,)\\s*");		

					person.setFirstName(names[0]);
					person.setLastName(names[1]);

					if (names[1].equalsIgnoreCase("and")) {
						person.setLastName(names[3]);
					}

					if (names.length == 2) {						
						person.setSpouseFirstName("");
						person.setSpouseLastName("");
					} else {
						person.setSpouseFirstName(names[2]);
						person.setSpouseLastName(names[3]);
					}

					address.setStreetNumber(streetInfo[0]);
					address.setStreetName(streetInfo[1]);
					address.setStreetType(streetInfo[2]);

					if(streetInfo.length == 3) {
						address.setStreetOrientation("");
					} else {
						address.setStreetOrientation(streetInfo[3]);
					}

					address.setCityName(cityProv[0]);
					address.setProvince(cityProv[1]);

					//records[3] is postal code, ignore

					output.format("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s%n", 
							person.getFirstName(), 
							person.getLastName(),
							person.getSpouseFirstName(),
							person.getSpouseLastName(),
							address.getStreetNumber(),
							address.getStreetName(),
							address.getStreetType(),
							address.getStreetOrientation(),
							address.getCityName(),
							address.getProvince());

					if ( nextLine.length() == 0 && input.hasNext())
						nextLine =input.nextLine();

					if (!input.hasNext()) {
						break;
					}
				}
			}
		}
		catch(IOException | NoSuchElementException | IllegalStateException e) {
			e.printStackTrace();
		}
		finally {
			input.close();
			output.close();			
		}
	}	
}
