package exam2011;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

/*
 * Utiliser une classe abstraite permet de factoriser du code.
 * Comme toutes les classes qui implémentent Ouvrage doivent contenir
 * un titre et un identifiant, on peut les définir, ainsi que les getters
 * correspondants dans une classe abstraite.
 * Dans ce cas, la classe Revue peut utilser cette classe abstraite, ce qui est fait
 * dans Revue2
 * 
 */

public abstract class AbstractOuvrage implements Ouvrage {
	private String titre;
	private long isbn;
	
	
	protected AbstractOuvrage(String titre, long isbn) {
		this.isbn = isbn;
		this.titre = titre;
	}

	@Override
	public long getISBN() {
		return isbn;
	}

	@Override
	public String getTitre() {
		return titre;
	}

	//Réponse à la question 4
	static LinkedList<Ouvrage> chargeOuvrages(String f) throws FichierOuvrageException {
		LinkedList<Ouvrage> l=new LinkedList<Ouvrage>();
		BufferedReader input=null;
			try {
				input=new BufferedReader(new FileReader(f));
				String line;
				while((line=input.readLine())!=null) {
					if(line.length()!=1)
						throw new FichierOuvrageException("L or R expected");
					char typeOuvrage=line.charAt(0);
					if((line=input.readLine())==null)
						throw new FichierOuvrageException("ISBN expected");
					long isbn=Long.parseLong(line);
					if((line=input.readLine())==null)
						throw new FichierOuvrageException("Title expected");
					String titre=line;
					switch(typeOuvrage) {
					case 'R' :
						if((line=input.readLine())==null)
							throw new FichierOuvrageException("Revue number expected");
						int numero=Integer.parseInt(line);
						if((line=input.readLine())==null
								|| !line.equals("#"))
							throw new FichierOuvrageException("# expected");
						l.add(new Revue(titre, numero, isbn));
						break;
					case 'L' :
						LinkedList<String> auteurs= new LinkedList<String>();
						while(true) {
							if((line=input.readLine())==null)
								throw new FichierOuvrageException("Author or # expected");
							if(line.equals("#"))
								break;
							auteurs.add(line);
						}
						l.add(new Livre(titre,auteurs,isbn));
						break;
					default:
						throw new FichierOuvrageException("L or R expected");
					}
				}
			} catch (FileNotFoundException e) {
				throw new FichierOuvrageException("File not Found");
			} catch (IOException e) {
				throw new FichierOuvrageException("Input Exception");
			} finally {
				if(input!=null)
					try {
						input.close();
					} catch (IOException e) {
						throw new FichierOuvrageException("Input Close error");
					}
			}
		
		return l;
	}
	
}
