package app.controllers;

import javafx.fxml.FXML;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.ResourceBundle;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

import app.events.OpenFileEvent;
import app.events.OpenProjectEvent;
import app.events.SaveFileEvent;
import app.model.Model;
import app.service.DialogBoxes;
import app.service.FiletreeOperations;
import javafx.fxml.Initializable;

/**
 * A FXML controller that controls the filetree component of the UI
 */
public class FiletreeController implements Initializable, Controller {

  private EventBus eventBus;

  @FXML
  private TreeView<String> filetree;

  @Override
  public void initialize(URL url, ResourceBundle resourceBundle) {}

  @Override
  public void setEventBus(EventBus eventBus) {
    this.eventBus = eventBus;
    this.eventBus.register(this);
  }

  /* ------------------------------------------------------------------------ */
  /* FILETREE */
  /* ------------------------------------------------------------------------ */

  /**
   * The displaying of the fileTree. The inputChosen(the path) is aquired from the
   * eventBus (OpeFileProjectEvent). The root is created as a CheckBoxItems and
   * sends it to generateTree, and after that setting it to the root.
   */
  private void showTree(String inputChosen) {
    CheckBoxTreeItem<String> root = new CheckBoxTreeItem<>(inputChosen);
    filetree.setShowRoot(false);
    File fileInputChosen = new File(inputChosen);

    try {
      FiletreeOperations.generateTree(fileInputChosen, root);

      filetree.setRoot(root);
    } catch (Exception e) {
      Model.setProjectPath(Optional.empty());
      DialogBoxes.showErrorMessage(
        "Could not open folder.\n\n"
        + "Do you have the right permissions for this folder?\n"
        + "Or does the folder contain any shortcut to somewhere within itself?");
    }
  }

  /* ------------------------------------------------------------------------ */
  /* MouseClick */
  /* ------------------------------------------------------------------------ */

  /**
   * Handles whenever a filetree item is clicked twice. A while loop to create the
   * correct filepath.
   */
  @FXML
  private void handleMouseClick(MouseEvent event) {
    if (event.getClickCount() == 2) {
      TreeItem<String> item = filetree.getSelectionModel().getSelectedItem();

      Path path = FiletreeOperations.getPathOfTreeItem(item);

      if (!Files.isDirectory(path)) {
        this.eventBus.post(new OpenFileEvent(Optional.ofNullable(path)));
      }
    }
  }

  /* ------------------------------------------------------------------------ */
  /* SUBSCRIPTIONS */
  /* ------------------------------------------------------------------------ */

  /**
   * Updates the filetree whenever a new ProjectPath is selected.
   */

  @Subscribe
  private void handle(OpenProjectEvent event) {
    this.showTree(event.getPath().toString());
  }

  @Subscribe
  private void handle(SaveFileEvent event) {
    if (event.getIsNewFile())
      Model
        .getProjectPath()
        .ifPresent(path -> this.showTree(path.toString()));
  }

}
