/**
 * Retrieves the appropriate file, given the file's name in string form. If category is specified, the file is read from the corresponding directory, otherwise all directories are tried systematically. Returns the file as a String.
 * @author Zachary Carter
 * @version 1.0
 * Created on Feb 10, 2005
 */
package thegroup.projectcddb.database;

import java.io.*;

public final class FileOpener implements ClientInterface {

  private String line = "";
  private String xmcdContent = "";
  private File file;
  private FileReader fileReader;
  private BufferedReader inFile;
  private String[] categories = {"lib/database/blues", "lib/database/classical", "lib/database/country", "lib/database/data", "lib/database/folk", "lib/database/jazz",
                                        "lib/database/misc", "lib/database/newage", "lib/database/reggae", "lib/database/rock", "lib/database/soundtrack"};

  /**
   * getCDDBFile Retrieves by discid the xmcd file specified by input parameter fileName from the CDDB database.
   *
   * @param category String The category/genre the discid represents, if available, null if not.
   * @param fileName String The discid of the desired xmcd file. The discid is the name of the file.
   * @return String The xmcd file in string form, with new lines separated by "\n". If file-not-found, return null.
   */
  public String getFile(String fileName) {
            //find which directory the file resides in, if any
          try {
                  file = new File("lib/database/blues", fileName);
                  for (int ctr = 0; !file.exists() && ctr < categories.length; ctr++){
                        thegroup.projectcddb.server.MultiServer.log.finest("File not found. Trying next directory.");
                        file = new File(categories[ctr], fileName);
                  }
                  if (!file.exists()) {
                  return null;
                  }
              //read input file from disk
              fileReader = new FileReader(file);
              inFile = new BufferedReader(fileReader);
              line = inFile.readLine();
              while (line != null) {
                xmcdContent += line;
                line = inFile.readLine();
                if (line != null){
                  xmcdContent += "\n";
                }
              }
              inFile.close();
            }
            catch (FileNotFoundException e) {
              System.out.println("File not found. Make sure input files exist.");
            }
            catch (IOException e) {
              System.out.println("Incorrect data format.");
            }
            catch (ArrayIndexOutOfBoundsException e){
              System.out.println("File not found. Make sure input files exist.");
            }
            catch (Exception e) {
              e.printStackTrace();
            }
            return xmcdContent;
  }
  
} //end class
