package WheelOfFortune.localManager;

import WheelOfFortune.storage.*;
import java.util.*;
import java.io.*;
import javax.swing.table.*;

public class LocalManager {
 private static final String localDir = ".\\puzzles\\";

 LocalManagerOutput out;
 String[] fileNames;
 String openFileName;
 boolean modified;


 Vector names;
 DefaultTableModel tm;






 public LocalManager(LocalManagerOutput out) {
  this.out = out;
  fileNames = null;
  tm = null;
  openFileName = null;
  modified = false;

  refreshFileList();

  names = new Vector();
  names.add("Solution");names.add("Category");

  tm = new MyTableModel(new Vector(),names);
  out.setPuzzleTableModel(tm);

out.puzzleTable.getTableHeader().setReorderingAllowed(false);
  
 }

 public void refreshFileList() {
  try {
  File f = new File(localDir);
  fileNames = f.list();
  out.setFileList(fileNames);
 }
 catch(Exception e) { System.out.println("Errorrrr"); }
 }

 public void openFile(int i) {
  try {
  String smallFileName = fileNames[i];
  String filename = localDir + smallFileName;


  saveIfNecessary();
  
  Vector v = Utilities.getPuzzleVector(filename);

  tm.setDataVector(v,names);
  openFileName = smallFileName;
  modified = false;
  }
  catch(Exception e) { }
 }

 public void newFile(String name) {
  try {
   File f = new File(localDir + name);
   boolean result = f.createNewFile();
   if(result == false) out.printErrorMessage("A file with that name already exists.");
   refreshFileList();
  }
  catch(Exception e) { }
 }

 public void deleteFile(int i) {
  try {
   String filename = localDir + fileNames[i];
   File f = new File(localDir + fileNames[i]);
   f.delete();
   refreshFileList();

   if(filename.equals(openFileName)) {
    modified = false;
    Vector v = new Vector();
    tm.setDataVector(v,names);
   }
   if(filename.equals(openFileName)) openFileName = null;
  }
  catch(Exception e) { }
 }


 public void startAdd() {
  if(openFileName == null) {
   out.printErrorMessage("You must open a file first.");
   return;
  }
  out.displayAddPuzzleDialog();
 }

 public void addPuzzle(String solution, String category) {
  if(openFileName == null) {
   out.printErrorMessage("You must open a file first.");
   return;
  }
  Vector v = new Vector();
  v.add(solution);
  v.add(category);
  tm.insertRow(tm.getRowCount(),v);
  modified = true;
 }


 public void deletePuzzle(int i) {
  if(openFileName == null) {
   out.printErrorMessage("You must open a file first.");
   return;
  }
  tm.removeRow(i);
  modified = true;
 }

 public void saveIfNecessary() {
  if(openFileName == null || modified == false) return;
  Vector v = tm.getDataVector();
  
  try {
  Utilities.storePuzzles(v, localDir + openFileName);
  }
  catch(Exception e) { }
 }

}