/* Comp1100 Sem 1, 2006
 * 
 * Supermarket Docket Example Program
 * 
 * Docket class is a _module_ collecting together the formatting
 * functions for laying out the printed docket.
 * Rather tedious and not very interesting.
 *
 * I have no idea what is the "best" way to manage this formatting
 * (i.e. justifying strings of various lengths on a fixed length line)
 * in Java.  Hence this is not to be taken as exemplary code.
 *
 * There are no objects of this class (cf. java.lang.Math) so I've
 * made all methods static.
 *
 * Clem Baker-Finch May 2006
*/

class Docket {

    // Set the line length for the docket layout
    static final Integer LINELENGTH = 30;
    // A blank line of 30 characters .. 
    //there's got to be a better way :-(
    static final String BLANKLINE = "                              ";

    // A function to centre-justify a string
    private static String cJustify(String str) {
	Integer len = str.length();
	String leadingBlanks = BLANKLINE.substring(0,(LINELENGTH - len)/2);
	return leadingBlanks + str;
    }

    // Format a price
    private static String formatCents(Integer price) {
	Integer dollars = price/100;
	Integer cents = price % 100;
	if (cents < 10)
	    return dollars + ".0" + cents;
	else
	    return dollars + "." + cents;
    }

    // The docket heading
    public static String heading() {
	return cJustify("Gosling's Sunny-Mart"); // + "\n";
    }

    // Format each line of the docket
    public static String formatLine(Product item) {
	// format the price
	String cost = formatCents(item.getPrice());
	String itemName = item.getName();
	// How many spaces needed?
	Integer numSpaces = LINELENGTH - itemName.length() - cost.length();
	String spaces = BLANKLINE.substring(0, numSpaces);
	return itemName + spaces + cost;
    }

    // Format the total cost line of the docket
    public static String formatTotal(Integer total) {
	// format the total cost
	String cost = formatCents(total);
	final String TOTAL = "TOTAL:";
	// How many spaces needed (1 less for "$")?
	Integer numSpaces = LINELENGTH - TOTAL.length() - cost.length() - 1;
	String spaces = BLANKLINE.substring(0, numSpaces);
	return TOTAL + spaces + "$" + cost + "\n";
    }

}

