/*=========================================================================
  ENCABEZADO DE LOS MODULOS (Bibliotecas) 
  =========================================================================*/
import java.io.*; /** Libreria para accesos de entrada y salida*/
import java.lang.Object.*;

/*=========================================================================
  ENCABEZADO DE LA CLASE 
  =========================================================================*/
/**
 * CLASE: Test.java
 * <br>OBJETIVO: Clase realiza la prueba de la clase <b> VideoCentro </b> y <b>PrecioInvalidoException.</b> Esta es una clase para manejar la interfaz en modo caracter.
 * ASIGNATURA: java basico
 * @version 1.0 24/07/2005
 * @author William Mendoza Rodr�uez;
 * @author DIANA FARIETTA
 */

public class Test {
    
    static BufferedReader entrada = new BufferedReader (new InputStreamReader (System.in));
    
    static String lectura = "";
    static String nombre = "";
    static String nuevo;
    static int copias;
    static float precio;
    static Pelicula p;
    static VideoCentro blockbuster;
  
    
    /*=========================================================================
      DEFINICION E IMPLEMENTACION DE LOS METODOS ANALIZADORES Y MODIFICADORES
      =========================================================================*/
    /**
     * Menu principal del Test.
     * <br> Presenta las opciones de:
     * <br> 0.- Salir: Sale del programa 
     * <br> 1.- Registro de Pel&iacute;culas: Adicionar una pel&iacute;cula al sistema.
     * <br> 2.- Consulta de Pel&iacute;cula: Consulta una pel&iacute;cula del sistema con un id espec&iacute;fico.
     * <br> 3.- Lista de Pel&iacute;culas: Listado de las pel&iacute;culas del sistema.
     * <br> 4.- Eliminacion de una Pel&iacute;culas: Elimina una pel&iacute;cula del sistema.
     * <br> 5.- Renta de Pelicula: Alquiler de una pel&icaute;cula del sistema 
     * <br>PRE: TRUE
     * @throws excepciones de entrada y salida
     */
    
    private static void menuPrincipal()  throws IOException  {
	
	  int opcion = 0;
	    
	  do {
	    System.out.println ("+----------------------------------------+");
	    System.out.println ("| SISTEMA DE ALQUILER DE VIDEOS          |");
	    System.out.println ("+----------------------------------------+");
	    System.out.println ("| 0- Salir                               |");
	    System.out.println ("| 1- Registro de Pelicula                |");
	    System.out.println ("| 2- Consulta de Pelicula                |");
	    System.out.println ("| 3- Lista de Peliculas                  |");
	    System.out.println ("| 4- Eliminacion de Pelicula             |");
	    System.out.println ("| 5- Renta de Pelicula                   |");
	    System.out.println ("+----------------------------------------+");
	    System.out.print ("\n");
	    System.out.print ("  Por favor escoja una opcion : ");
	    System.out.flush ();
	    
	    try {
		  opcion = Integer.valueOf (entrada.readLine()).intValue();
		  	switch (opcion) {
		        
		    	case 0: 					// 0- Salir del programa
		           	break;
		    
		    	case 1:						// 1- Registro de Pelicula
		    		registrarPelicula();
		    		break;
		    
		    	case 2:						// 2- Consulta de Pelicula
		    		consultarPelicula();
		    		break;
		    
		    	case 3:						// 3- Lista de Peliculas
		    		listarPeliculas();
		    		break;
		    
		    	case 4:						// 4- Eliminacion de Pelicula
		    		eliminarPelicula();
		   			break;
		    
				default:
		    		System.out.println ("\n   Intentelo de nuevo ! \n");
			} //switch
	    } //fin try
	    
	    catch (Exception e) {
			System.out.print ("*** ERROR: ");
			System.out.println (e + "\n");
			opcion = -1;
	    }
	     text=leerString("Desea continuar");	//esto se anexo o se modifico
	  } while (opcion != 0);		//fin while 
	
	
    } // fin menu principal
    
    /**
     * Metodo que realiza el registro de una Pelicula
     * <br>PRE: TRUE
     @throws excepciones de entrada y salida
    */
    
    private static void registrarPelicula() /*throws IOException*/  {
	
	int opcion = 0;
	String nuevo;
	String nombre;
	int anio=0;
	String id;
	float precio=0.0f;
	float duracion=0.0f;
	BufferedReader entrada = new BufferedReader (new InputStreamReader (System.in));
		
	do{
		nombre = leerString("Nombre de la Pelicula"); 	//leo el nombre (String)
		
		do{
			precio = leerFloat("Costo Renta"); 				//leo el precio de 	
			try {
		   	 	if (precio <= 0) 
					throw new PrecioInvalidoException();
				else
					break;
			}
			catch (PrecioInvalidoException e){
				System.out.println("*** ERROR: " + e.toString());
			}
		} while (true);						//Fin del While
		
		
		do{
			anio = leerInt("Anio de estreno");				//leo el a� de estreno (entero)
			try{
				if((anio<1900)||(anio>2005))
					throw new AnioInvalidoException();
				else
					break;
			}
			catch (AnioInvalidoException e){
				System.out.println("*** ERROR: " + e.toString());
			}
		} while (true);
        
		
		do{
			duracion = leerFloat("Duracion en minutos");	//leo la duraci� de la pelicula en minutos
			try{
				if(duracion<=0)
					throw new DuracionInvalidaException();
				else
					break;		
			}
			catch(DuracionInvalidaException e){
				System.out.println("*** ERROR: " + e.toString());
			}
				
		} while (true);
		
				
		id = leerString("Identificador de la pelicula");
//Imprimo los datos
		System.out.println ("La pelicula es " + nombre + ", se estreno el anio " + anio +" y su alquiler es de $" + precio); 
	
			// HAGA LO NECESARIO PARA TERMINAR DE LEER TODOS LOS DATOS Y CREAR PELICULAS NUEVAS 
        	// AGREGANDOLAS A Videocentro Y MOSTRARLAS DESPUES DE SALIR DEL CICLO
	 	
	 	p = new Pelicula();
		
		p.setId(id);
		p.setNombre(nombre);
		p.setAgno(anio);
		p.setDuracion(duracion);
		p.setCostoAlquiler(precio);
		
		blockbuster.registrar(p);             
		
		nuevo = leerString("Desea ingresar otra pelicula [s/n]"); 
	}
	while(text.equals("s")); 	
    }
    
    /**
     * Metodo que realiza la consulta de una Pelicula 
     * <BR>PRE: TRUE
     * @throws excepciones de entrada y salida
     */
    private static void consultarPelicula() /*throws IOException*/ {
    	
    	String movie;
    	String llave;
    	
    	
   		llave = leerString("Identificador de la pelicula");
   		
   		try {
   			if (blockbuster.existeLlave(llave)== true){
   				movie = blockbuster.getInfo(llave);
   				System.out.println("Estos son los datos de la pelicula: \n" + movie +"\n");
   			}
   			else
   				throw new LlaveInvalidaException();
   		}
    	catch(LlaveInvalidaException e){
    		System.out.println("*** ERROR: " + e.toString());
    	}
   	}
    
    /**
     * Metodo que realiza el listado de las Peliculas 
     * <BR>PRE: TRUE
     * @throws excepciones de entrada y salida
     */
    private static void listarPeliculas() throws IOException  {
		String Lista;
		Lista = blockbuster.toString();
		
		System.out.println("Estas son todas las peliculas del VideoCentro: \n" + Lista + "\n");
		
    }
    
    /**
     * Metodo que realiza la eliminacion de una Pelicula 
     * <BR>PRE: TRUE
     * @throws excepciones de entrada y salida
     */
    private static void eliminarPelicula() /*throws IOException*/ {
    	String llave;
    	String opcion;
    	boolean resp;
    	
    	llave = leerString("Identificador de la pelicula");
		
		try{
			if (blockbuster.existeLlave(llave) == true){
				opcion = leerString("Esta seguro de eliminar la pelicula: [S/N]");
				if(opcion.equalsIgnoreCase("S")){
					resp = blockbuster.eliminar(llave);
					if(resp == true)
						System.out.println("Pelicula Eliminada del sistema!.");
					else
						System.out.println("La Pelicula no ha podido ser eliminada!.");
				}
			}
			else
				throw new LlaveInvalidaException();
		}
		catch(LlaveInvalidaException e){
    			System.out.println("*** ERROR: " + e.toString() + "\n");
		}
	}
    
    /**
     * Retorna el String que lee del Teclado. 
     * <br>PRE: TRUE
     * <br>POS: Lo que se digita del teclado en String.
     * @param Mensaje que se muestra en Pantalla.
     * @return El String que leyo. En caso de no poder convertirlo a String retorna un caracter vacio.
     */

    static String leerString (String mensaje) {
	String ent="";
	do {
	    System.out.print (mensaje + " ? ") ;
	    try {
			ent = entrada.readLine();
		break;
	    }
	    catch (IOException e) 
		{
		    System.out.println (e) ;
		}
	} 
	while (true);
	return ent;
    }
  
    
    /**
     * Metodo que lee un int del Teclado 
     * <br>PRE: TRUE
     * <br>POS: Lo que se digita del teclado en String.
     * @param Mensaje que se muestra en Pantalla.
     * @return El entero que ley&o.
     */
    
    static int leerInt (String mensaje) {
	int ent;
	do {
	    System.out.print (mensaje + " ? ") ;
		
		try {
			ent = Integer.parseInt(entrada.readLine());
		break;
	    }
	    catch (IOException e) 
		{
		    System.out.println (e) ;
		}
	} 
	while (true);
	return ent;
    }
  
    /**
     * M&etodo que lee un float del Teclado 
     * <br>PRE: TRUE
     * <br>POS: Lo que se digita del teclado en String.
     * @param Mensaje que se muestra en Pantalla.
     * @return El float que ley&o.
     */
  
    static float leerFloat(String mensaje) {
	float  ent;
	do {
	    System.out.print (mensaje + " ? ") ;
		try {
			ent = Float.parseFloat (entrada.readLine());
			break;
	    }
	    catch (IOException e) 
		{
		    System.out.println (e) ;
		}
	} 
	while (true);
	return ent;
    }
    
    
    /**
     * Metodo que lee un double del Teclado 
     * <br>PRE: TRUE
     * <br>POS: Lo que se digita del teclado en String.
     * @param Mensaje que se muestra en Pantalla.
     * @return El double que leyo.
     */
  
    static double leerDouble(String mensaje) {
	double  ent;
	do {
	    System.out.print (mensaje + " ? ") ;
		
		try {
			ent = Double.parseDouble (entrada.readLine());
			break;
	    }
	    catch (IOException e) 
		{
		    System.out.println (e) ;
		}
		
		
	} 
	while (true);
	return ent;
    }
  
    /*=========================================================================
      PROGRAMA PRINCIPAL 
      =========================================================================*/
    /**
     * Realiza el Menu Principal.
     * @throws excepciones de entrada y salida
     */    
    public static void main(String[] args) throws Exception {
        
        blockbuster = new VideoCentro();
        menuPrincipal();
        System.out.println("El Programa a Finalizado Satisfactoriamente");
    }
}

