import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;

/**
 * Brute force solution to HW1A, totaling sales invoices.
 *   @author Dave Reed
 *   @version 1/29/15
 *
 */
public class TotalSales1 {

	public static void main(String[] args) {
		ArrayList<String> invoices = new ArrayList<String>();
		
		System.out.print("Enter the sales file name: ");
		Scanner input = new Scanner(System.in);
		String filename = input.next();
		try {
			int totalUnits = 0;
			double totalSales = 0.0;
			Scanner infile = new Scanner(new File(filename));
			while (infile.hasNext()) {
				String date = infile.next();
				String customer = infile.next();
				int units = infile.nextInt();
				double price = infile.nextDouble();
				String salesPerson = infile.next();
				
				String newInvoice = date+" "+customer+" "+units+" "+price+" "+salesPerson;
				TotalSales1.addInOrder(invoices, newInvoice);
				
				totalUnits += units;
				totalSales += units * price;
			}
			infile.close();
			
			System.out.println();
			for (String nextInvoice : invoices) {
				System.out.println(nextInvoice);
			}
			System.out.println("Total units = " + totalUnits);
			System.out.println("Total sales = $" + totalSales);
		}
		catch (java.io.FileNotFoundException e) {
			System.out.println("Sales file not found.");
		}
		input.close();
	}
	
	/**
	 * Helper function for comparing two date strings of form MM-DD-YYYY.
	 * @param date1 the first date
	 * @param date2 the second date
	 * @return true if date1 comes before date2
	 */
    private static boolean comesBefore(String date1, String date2) {
		String dateParts1[] = date1.split("-");
		String dateParts2[] = date2.split("-");
		
		if (Integer.parseInt(dateParts1[2]) != Integer.parseInt(dateParts2[2])) {
			return Integer.parseInt(dateParts1[2]) < Integer.parseInt(dateParts2[2]);
		}
		else if (Integer.parseInt(dateParts1[0]) != Integer.parseInt(dateParts2[0])) {
			return Integer.parseInt(dateParts1[0]) < Integer.parseInt(dateParts2[0]);
		}
		else {
		    return Integer.parseInt(dateParts1[1]) < Integer.parseInt(dateParts2[1]);
		}
	}
	
    /**
     * Adds an invoice string to the list in order by date.
     * @param invoices the list of invoice strings
     * @param newInvoice the new invoice string to be added
     */
	private static void addInOrder(ArrayList<String> invoices, String newInvoice) {
		invoices.add(newInvoice);
		int index = invoices.size()-1;
		while (index > 0 && TotalSales1.comesBefore(invoices.get(index).split(" ")[0],
				                                    invoices.get(index-1).split(" ")[0])) {
	        invoices.set(index, invoices.get(index-1));
	        invoices.set(index-1, newInvoice); 
	        index--;
		}  
	}
}