//
// ****************************************************
//
//      Gregg L. Zepp II
//
//      Intro to Java Programming
//
//      Hardware Store Inventory program initializes 
//      a random-access file to 100 empty records, 
//      then lets one input data for a new tool, list 
//      tool records, delete a tool record, and update 
//      a tool's record.
//
//      HW #6, Exercise 14.11 P.741
//
// ****************************************************
import java.util.*;
import java.io.*;
import java.text.*;

public class HardwareStore
{
	Vector tools; // holds records for type Tool
	String f = "hardware.dat"; // holds file information
	BufferedReader reader; // read from keyboard
   
	public static void main(String[] args) //main method
   {
      HardwareStore obj=new HardwareStore(); //called to initialize obj.initializationFile
   } // end main method
   
   
	public HardwareStore() // class constructor
	{
		reader=new BufferedReader(new InputStreamReader(System.in));
		tools=new Vector(0); // initializes vector
      
		loadFromFile(); //call method to read data from file
		menu(); // call the menu
   } // end constructor
	
   
	private void initializationFile() // initialize file
	{
	 	try
         {
			   RandomAccessFile file = new RandomAccessFile(f, "rw"); //initializes file
		
			   //from assignment and are stored to file
			   file.writeUTF(1+" Sander 18 35.99\n");
			   file.writeUTF(2+" Hammer 128 10.00\n");
			   file.writeUTF(3+" Jigsaw 16 14.25\n");
			   file.writeUTF(4+" Mower 10 79.50\n");
			   file.writeUTF(5+" Saw 8 89.99\n");
			   file.writeUTF(6+" Screwdriver 236 4.99\n");
			   file.writeUTF(7+" Sledgehammer 32 19.75\n");
			   file.writeUTF(8+" Wrench 65 6.48\n");
			
			   for(int i=9;i<=100;i++) //creates empty records
            {
				   file.writeUTF(i+" "+"x"+" "+0+" "+0+"\n");
            }
			   file.close(); //close the file
            
         } // end try block
         
      catch (Exception e)
         {
            System.out.println("\nError initializing file."+e);
         }
		
		menu(); //back to menu
   } // end initializationFile

   
	private void loadFromFile() // loads file
	{
      try
         {
		      RandomAccessFile file = new RandomAccessFile(f, "rw");
		
		      for(int i=1;i<=100;i++) //reads 100 elements in from the file
			      {
				      String line=file.readUTF(); //read next line of text
                  //each line of text is converted to an object of class tool
				      Tool currentTool=stringToTool(line); 
				      tools.add(currentTool); //the object is stored to an Vector
               }
		      file.close(); // close file
            
         } // end try block
      
       catch (Exception e) //handles exceptions
          {
             System.out.println("Error loading from file."+e);
          }
   } // end loadFromFile

   
	private Tool stringToTool(String a) //converts a string to an object of type Tool
	{
		Tool obj=new Tool(); //new object
		StringTokenizer tok=new StringTokenizer(a); //used to parse the string

		obj.number=Integer.parseInt(tok.nextToken()); //read number and convert it to int
		obj.name=tok.nextToken(); //read and convert name
		obj.quantity=Integer.parseInt(tok.nextToken()); //read and convert quantity
		obj.cost=Double.parseDouble(tok.nextToken()); //read and convert cost
		
		return obj; //return the new created object
   } // end stringToTool

   
   private void inputTool() //reads a new record from the keyboard
   {
      int recordNumber=0,quantity=0;
      String name="";
      double cost=0;
   
      System.out.println("\nWARNING! New data will override prior record " +
                          "if the same record number is choosen.");
      
      Tool newObj=new Tool(); //stores the data
      
      try
         {
            //reads in all atributes of the new record to create
            System.out.print("Record number: ");
            recordNumber=Integer.parseInt(reader.readLine());
            
            System.out.print("name: ");
            name=reader.readLine();
         
            System.out.print("quantity: ");
            quantity=Integer.parseInt(reader.readLine());
            
            System.out.print("cost: $");
            cost=Double.parseDouble(reader.readLine());
            
         } // end try block
      
         catch(Exception e)
            {
               System.out.print("Error entering information! Please Re-enter...\n"+e);
            }
   
         //assign the values read from keyboard to the object
         newObj.name=name;
         newObj.quantity=quantity;
         newObj.cost=cost;
      
         //store the object at the right location in the Vector   object
         tools.setElementAt(newObj,(recordNumber-1));
   
         menu(); // back to menu
   } // end inputTool

	private void listRecords() //list all records
	{
		System.out.println("\nHardware Store Inventory Records:");
		
		for(int i=0;i<100;i++)
		   {
			   Tool currentTool=(Tool)(tools.elementAt(i)); //stores record as temporary data
            if(!currentTool.name.equals("x")) //prints just the exception
            {
               System.out.println("Record #"+(i+1)+", name: "+
               currentTool.name+", value: $"+
               toDollarForm(currentTool.cost)+", quantity: "+
               currentTool.quantity);
            } 
      
          } // end for statement 
      
		menu(); //back to menu
   } // end listRecords

   private void delete() //used to delete records
   {
      int number=0; // sets number
      Tool empty=new Tool(); // sets record
      
      System.out.println("\nPlease enter the record number to delete: ");
      
      try
         {
            //create the number of record to delete
            number=Integer.parseInt(reader.readLine());
      
            System.out.println(">>>Deleting record: "+tools.get(number).toString());
            tools.setElementAt(empty,number-1); //replace the record with an empty one
            
         } // end try block
      
      catch(Exception e)
         {
            System.out.println("\nError entering choice! Please Re-enter...\n");
         }

      menu(); // back to menu
   } // end delete
   
	private void update() //updates a record details
	{
		int recordNumber=0; // sets record number 
		int quantity=0; // sets quantity
		String name=""; // sets name
		double cost=0; // sets cost

		Tool newObj=new Tool(); //stores data for the new object, read from the keyboard
		
		try
         {
			   //reads in all atributes of the new record to create
			   System.out.print("\nPlease enter the record number to update: ");
			   recordNumber=Integer.parseInt(reader.readLine());
			
			   System.out.print("\nRecord details: ");
			   //prints out the details of the object to modify
			   System.out.println(((Tool)(tools.get(recordNumber-1))).toString());
			
			   System.out.print("name: ");
			   name=reader.readLine();
			
			   System.out.print("quantity: ");
			   quantity=Integer.parseInt(reader.readLine());
				
			   System.out.print("cost: $");
			   cost=Double.parseDouble(reader.readLine());
			
         } // end try block
      
      catch(Exception e)
         {
            System.out.print("Error reading data! Please Re-enter...\n"+e);
         }
	
		//assign inputed values read from keyboard to their objects
		newObj.name=name; 
		newObj.quantity=quantity; 
		newObj.cost=cost;
		
		//store the object at the right location in the Vector object
		tools.setElementAt(newObj,(recordNumber-1));

		menu(); //back to menu
   } //end update 

   private void save() //after all changes made, saves data from Vector object to the file
   {
      try
         {
            RandomAccessFile file = new RandomAccessFile(f, "rw");
      
            for(int i=0;i<100;i++) //100 records in Vector object are stored to file
               {
                  Tool currentTool=(Tool)(tools.elementAt(i)); //current tool
                  
                  //save each atribute of the tool object
                  file.writeUTF((i+1)+" "+currentTool.name+" "
                  +currentTool.quantity+" "+toDollarForm(currentTool.cost)+"\n"); 
               }                 
            file.close(); // closes file
            
          } // end try block

      catch (Exception e)
         {
            System.out.println("Error while saving to file! "+e);
         }
      
      menu(); // back to menu    
   } // end save
   
   
	private String toDollarForm(double in) //returns a double number in the format ##.##
	{
		String out="";
		DecimalFormat myformat = new DecimalFormat("0.00");
		out=myformat.format(in);
		return out;
   } // end toDollarForm

	private void printMenu() //prints the menu text
	{
		System.out.print("\nHardware Store Inventory Program:");
		System.out.print("\n1 - Input tool");
		System.out.print("\n2 - List all tools");
		System.out.print("\n3 - Delete tool");
		System.out.print("\n4 - Update tool");
		System.out.print("\n5 - Save to file");
		System.out.print("\n6 - Quit program");
		System.out.print("\n\nPlease enter Command: ");
   } // end printMenu
	
	private void menu() //reads command from the user and processes request
	{
		char command=' '; //stores the command
		printMenu(); //prints the menu
			
		try
         {
			   //command is the first char inserted from the keyboard
			   command=(reader.readLine()).charAt(0);
			
			   //each command has a method that does the requested thing
			   switch(command)
				   {
				      case '2' : listRecords();
                     break;
				      case '3' : delete();
                     break;
				      case '1' : inputTool();
                     break;
				      case '4' : update();
                     break;
				      case '6' : System.exit(1);
				      case '5' : save();
                     break;
                  default: System.out.println("\nNOT A MENU OPTION. Please choose again...");
				      menu(); // back to menu
               } // end switch
            
         } // end try block
      
      catch(IOException e) //handles exception
		   {
            System.out.print("Error reading command... "+e);
         }   
   } // end menu
  
} // end class HardwareStore

