///////////////////////////////////////////////////////////////////////////////
// Title:            InteractiveDBTester (Programming Assigning #1)
// Files:            
// Semester:         CS367 Summer 2014 (at Epic)
//
// Author:           Jason Roberts
// Email:            jjroberts345@gmail.com
// CS Login:         jroberts8
// Lecturer's Name:  Beck Hasti
///////////////////////////////////////////////////////////////////////////////

import java.util.*;
import java.io.*;
/**
 * The IterativeDBTester class will take input from the user to identify an input file,
 * load the input file into the Customer Database, and present the user
 * with options for interacting with the database. 
 * 
 */
public class InteractiveDBTester {
    
	public static void main(String[] args) throws IOException {
        CustomerDatabase DB = new CustomerDatabase();  		// create new CustomerDatabase
        
		// create scanner for console input stream
		Scanner stdin = new Scanner(System.in);
		
		// ask the user for a filename, pass console input Scanner as parameter
		// if no filename return "Please provide input file as command-line argument" and exit
		String fileName = getFileName(stdin);
	    	
	    // create a file object using the given filename
		// return "Cannot access input file" and exit if the file cannot be accessed
		File file = getFile(fileName);
   
    	// Load the data from the input file and use it to construct a customer database
    	buildDB(DB,file);
		
        // enter into the user interactive input and output
        // pass consult input Scanner as parameter
        reports(DB,stdin);
        
        // user is done, close the consult input scanner
        stdin.close();
	}
        
		/**
		 * Read from the text file and create a customers database
		 * 
		 * @param file- a File input from command line argument
		 * @throws IOException- can throw a FileNotFoundException when creating a new Scanner for the file
		 */
		private static void buildDB(CustomerDatabase DB, File f) throws IOException {
			Scanner inFile = new Scanner(f);							// Create file Scanner, can throw FileNotFoundException
            
			while ( inFile.hasNext() ) {								// loop through file line by line
            	String line = inFile.nextLine();   						// read the next line
            	line = line.toLowerCase();  							// convert input to lower case
            	List<String> list = Arrays.asList(line.split(","));		// split into a list using comma delimiter
                String custName = list.get(0);							// get customer name; always in position 0 in list
                DB.createCust(custName);								// add Customer to the database if not already there
                
                for (int i = 1; i < list.size(); i++) {					// loop through list of products in the line from the file
                	String prodName = list.get(i);						
                	DB.creatProd(prodName);								// add Product to the database if not already there
                	DB.addCustToProd(prodName, custName); 				// add the customer name to the Product object if not there 
                	DB.addProdToCust(custName, prodName);				// add the product name to the Customer object if not there
                }
            }
            inFile.close();  											//close the Scanner object attached to the file
        }
		
		/**
		 * Ask the user what report option they want and print the results to the screen
		 * 
		 * @param stdin- Scanner, the console input Scanner
		 */
        private static void reports(CustomerDatabase DB, Scanner stdin) {
	        printOptions();
	        boolean done = false;
	        while (!done) {
	            System.out.print("Enter option ( dfhisqr ): ");
	            String input = stdin.nextLine();
	            input = input.toLowerCase();  // convert input to lower case
	
	            // only do something if the user enters at least one character
	            if (input.length() > 0) {
	                char choice = input.charAt(0);  // strip off option character
	                String remainder = "";  // used to hold the remainder of input
	                if (input.length() > 1) {
	                    // trim off any leading or trailing spaces
	                    remainder = input.substring(1).trim(); 
	                }
	
	                switch (choice) {
	                
	                case 'd':
	                    // discontinue the given product, display "product discontinued"
	                	// or "product not found"
	                	if (DB.removeProduct(remainder)) {
	                		System.out.println("product discontinued");
	                	}
	                	else {
	                		System.out.println("product not found");
	                	}
	                    break;
	
	                case 'f':
	                    // return customer and their wishlist of products, or "customer not found"
	                	System.out.println(DB.custInfo(remainder));
	                    break;
	
	                case 'h': 
	                    printOptions();
	                    break;
	
	                case 'i':
	                	// display total number of customers and total number of unique products                
	                	System.out.println(DB.totals());
	                	
	                	// display stats relating to products per customer
	                	System.out.println(DB.custStats());
	                		                	
	                	// display stats relating to customers per product
	                	System.out.println(DB.prodStats());
	                	
	                	// display the most popular product
	                	System.out.println(DB.mostPopular());
	                	break;
	                    
	                case 's':
	                    // return a product and customers interested in it, or "product not found"
	                	System.out.println(DB.prodInfo(remainder));
	                    break;
	
	                case 'q':
	                    done = true;
	                    System.out.println("quit");
	                    stdin.close();  					//close console input Scanner
	                    break;
	
	                case 'r':
	                    // remove given customer, return "customer removed" or "customer not found"
	                	if (DB.removeCustomer(remainder)) {
	                		System.out.println("customer removed");
	                	}
	                	else {
	                		System.out.println("customer not found");
	                	}
	                    break;
	
	                default:  // ignore any unknown commands
	                    break;
	                }
	            }
	        }
	    }

    /**
     * Prints the list of command options along with a short description of
     * one.  This method should not be modified.
     */
    private static void printOptions() {
        System.out.println("d <product> - discontinue the given <product>");
        System.out.println("f <customer> - find the given <customer>");
        System.out.println("h - display this help menu");
        System.out.println("i - display information about this customer database");
        System.out.println("s <product> - search for the given <product>");
        System.out.println("q - quit");
        System.out.println("r <customer> - remove the given <customer>");
    }
   
    /**
     * ask the user for a filename- warn them and quit if they don't pass one in
     * 
     * @return myFileName- String,  provided by user, otherwise exit
     */
	private static String getFileName(Scanner stdin) {
		System.out.print( "Enter the filename: " );   	// prompt user for a file name
	    String myFileName = stdin.nextLine();        	// get file name from the user
	    if (myFileName.length() <1 ) {					// check if the user passed in a filename
	    	System.out.println("Please provide input file as command-line argument");
	    	stdin.close();  							// close console input Scanner
	    	System.exit(0);  						  	// exit, user didn't pass in a filename
	    }
		return myFileName;
	}
	
	/**
	 * create a file object using the given filename and quit if it cannot be accessed
	 * 
	 * @param fileName- String, filename provided by user
	 * @return myFile- File, if it exists, otherwise exit
	 */
	private static File getFile(String fileName) {
	    File myFile = new File( fileName );             	// create File object
	    if (!myFile.exists() ) {                        	// check that we could access the file
	    	 System.out.println("Error: Cannot access input file");
	    	 System.exit(0);  								//exit, could not access the file
	 	    }
	    return myFile;
	}
}	
	
	
	
	
	
	
	
	
	
	