// Implementation file for the shop program.

/*
 * Purpose:
 *   Takes shopping list data and prints a nicely formatted
 *   table of the data.
 *
 * Input:
 *   A file of item data containing a line of data for each
 *   item. The item fields on each line are separated by tab
 *   characters.
 *
 * Output:
 *   A tabular interpretation of the data in the input file.
 *
 * Usage:
 *   shop ITEM_FILE
 *
 * Classes:
 *    ShoppingList, Item
 *
 * Modified:
 *   27-AUG-2002 Scott Fleming
 */

#include <iostream>
#include <fstream>
using namespace std;
#include "ShoppingList.h"

/*
 * Purpose:
 *   Prints a decorative title box to an output stream.
 *
 * Preconditions:
 *   sout is open for output
 */
void printTitle(ostream &sout);

/*
 * Purpose:
 *   Prints a neatly formatted table of all the data stored in
 *   slist.
 *
 * Preconditions:
 *   sout is open for output
 */
void printList(const ShoppingList &slist, ostream &sout);


int main(int argc, char **argv) {
  Item item;
  ShoppingList slist;
  ifstream fin;

  if (argc != 2) {
    cerr << "usage: " << argv[0] << " INPUT_FILE\n";
    exit(1);
  }

  fin.open(argv[1], ios::in);
  if (!fin) {
    cerr << "error: Unable to open \"" << argv[1] << "\" for input\n";
    exit(1);
  }

  item.input(fin);
  while (!fin.fail()) {
    slist.insert(item, 0);
    item.input(fin);
  }

  fin.clear();
  fin.close();

  printTitle(cout);
  printList(slist, cout);
  cout.setf(ios::fixed | ios::showpoint);
  cout.precision(2);
  cout << "\nTotal Cost = $" << slist.getTotalCost() << "\n\n";

  return 0;
}


void printTitle(ostream &sout) {
  sout << "             ________________\n"
       << "            /               /\\\n"
       << "           / Shopping List /\\/\n"
       << "          /_______________/\\/\n"
       << "          \\_\\_\\_\\_\\_\\_\\_\\_\\/\n\n";
}


void printList(const ShoppingList &slist, ostream &sout) {
  Item anItem;
  int i;
  int n;

  n = slist.getSize();
  sout << "+----------------------+-------+---------+\n"
       << "|         Name         | Quant |  Cost   |\n"
       << "+----------------------+-------+---------+\n";
  for (i = 0; i < n; i++) {
    anItem = slist.getItemAt(i);
    anItem.output(sout);
  }
  sout << "+----------------------+-------+---------+\n";
}
