package WheelOfFortune.localManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class LocalManagerInput {
 LocalManager lm;
 LocalManagerOutput out;

 public LocalManagerInput(LocalManager lm, LocalManagerOutput out) {
  this.lm = lm;
  this.out = out;

  out.getRefreshBtn().addActionListener(new PuzzleListener());
  out.getOpenBtn().addActionListener(new PuzzleListener());
  out.getNewFileBtn().addActionListener(new PuzzleListener());
  out.getDeleteFileBtn().addActionListener(new PuzzleListener());


  out.getDeleteBtn().addActionListener(new PuzzleListener());
  out.getAddBtn().addActionListener(new PuzzleListener());
  out.getAddPuzzleBtn().addActionListener(new PuzzleListener());
  out.getClearPuzzleBtn().addActionListener(new PuzzleListener());

  out.getMainFrm().addWindowListener(new MyWindowListener());
 }

 private void openFile() {
  int i = out.getFileList().getSelectedIndex();
  if(i == -1) return;
  lm.openFile(i);
 }

 private void newFile() {
  String name = JOptionPane.showInputDialog(out.getMainFrm(), "Enter Filename", "New File", JOptionPane.QUESTION_MESSAGE);
  if(name != null && name.equals("") == false) lm.newFile(name);
 }

 private void deleteFiles() {
  int[] indexes = out.getFileList().getSelectedIndices();

  //has to go backwards so deleting doesn't screw up the other indices
  for(int i = indexes.length - 1;i >= 0;--i) {
   lm.deleteFile(indexes[i]);
  }
 }

 private void deletePuzzles() {
  int[] rows = out.getPuzzleTable().getSelectedRows();

  //has to go backwards so deleting doesn't screw up the other indices
  for(int i = rows.length - 1;i >= 0;--i) {
   lm.deletePuzzle(rows[i]);
  }
 }

 private void startAdd() {
  lm.startAdd();
 }

 private void clear() {
  out.clearPuzzle();
 }

 private void add() {
  String solution = out.getSolutionFld().getText();
  String category = out.getCategoryFld().getText();
  lm.addPuzzle(solution, category);
  out.clearPuzzle();
 }

 private class PuzzleListener implements ActionListener {
  public void actionPerformed(ActionEvent ae) {
   if(ae.getSource().equals(out.getRefreshBtn())) lm.refreshFileList();
   if(ae.getSource().equals(out.getOpenBtn())) openFile();
   if(ae.getSource().equals(out.getNewFileBtn())) newFile();
   if(ae.getSource().equals(out.getDeleteFileBtn())) deleteFiles();

   if(ae.getSource().equals(out.getDeleteBtn())) deletePuzzles();
   if(ae.getSource().equals(out.getAddBtn())) startAdd();
   if(ae.getSource().equals(out.getClearPuzzleBtn())) clear();
   if(ae.getSource().equals(out.getAddPuzzleBtn())) add();
  }
 }

 private class MyWindowListener extends WindowAdapter {
  public void windowClosing(WindowEvent e) {
   lm.saveIfNecessary();
   out.getMainFrm().dispose();
   out.getMM().setVisible(true);
  }
 }
}