package WheelOfFortune.storage;

import java.io.*;

// Source file: U:\\cse308\\asn8\\src\\storage\\LocalDatabase.java


public class LocalDatabase {
 private String directory;
 private PuzzlePackage[] packages;
   
 /**
  * @param directory
  * @roseuid 418934D803A8
  */
 public LocalDatabase(String directory) {
  this.directory = directory;
  packages = null;
  try {
  String[] filenames = new File(directory).list();
  packages = new PuzzlePackage[filenames.length];
  for(int i = 0;i < filenames.length;++i) {
   packages[i] = new PuzzlePackage(directory + "\\" + filenames[i]);
   }
  }
  catch(Exception e) {}
  for(int i = 0;i < packages.length;++i) {
  }
 }
 
 /*this is messy, clean it up later*/ 
 public Puzzle getRandomPuzzle() {
  Puzzle p = null;
  int totalPuzzles = getNumPuzzles();
  if(totalPuzzles == 0) return null;
  int target = (int)(Math.random() * totalPuzzles);
  int lastIndexChecked = -1;
  int i;
  for(i = 0;i < packages.length;++i) {
   if(lastIndexChecked + packages[i].getNumPuzzles() >= target) break;
   lastIndexChecked += packages[i].getNumPuzzles();
  }
  int firstIndexOfFile = lastIndexChecked + 1;
  int puzzleIndex = target - firstIndexOfFile;
  p = packages[i].getPuzzle(puzzleIndex);
  return p;
 }
   
 public int getNumPuzzles() {
  int count = 0;
  for(int i = 0;i < packages.length;++i) {
   count += packages[i].getNumPuzzles();
  }
  return count;
 }
}
