package app.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Scanner;

import app.model.Model;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class FileOperations {

  // FIXME: This class contains bugs when opening fiies and folders.
  // TODO: Needs documentation and cleanup
  // TODO: This class needs to be extensively error checked

  public static File openFileWithDialog(Stage stage) throws FileNotFoundException {

    FileChooser fc = new FileChooser();
    fc.setTitle("Open File");

    File chosenFile = fc.showOpenDialog(stage);

    if (chosenFile == null)
      throw new FileNotFoundException();

    return chosenFile;

  }

  public static File openFolderWithDialog(Stage stage) throws FileNotFoundException {

    DirectoryChooser dc = new DirectoryChooser();
    dc.setTitle("Open Project");

    File dir = dc.showDialog(stage);

    if (dir == null)
      throw new FileNotFoundException();

    return dir;
  }

  public static boolean saveFile(Path filepath, String content) {
    try (PrintWriter writer = new PrintWriter(filepath.toFile())) {
      writer.println(content);
      return true;

    } catch (FileNotFoundException ex) {
      DialogBoxes.showErrorMessage("Could not save file at \n" + filepath.toString());
      return false;
    }
  }

  public static boolean saveFileWithDialog(Stage stage, String content) {
    FileChooser fc = new FileChooser();
    fc.setTitle("Save as");

    Model
      .getProjectPath()
      .ifPresent(path -> fc.setInitialDirectory(path.toFile()));

    File chosenLocation = fc.showSaveDialog(stage);
    if (chosenLocation == null)
      return false;

    if (saveFile(chosenLocation.toPath(), content)) {
      Model.setActiveFilePath(Optional.of(chosenLocation.toPath()));
      return true;
    }

    return false;
  }

  public static String readFile(Path filePath) {

    if (filePath == null)
      return "";

    String result = "";

    try (Scanner sc = new Scanner(filePath.toFile())) {
      while (sc.hasNextLine()) {
        result += (sc.nextLine() + "\n");
      }

    } catch (FileNotFoundException ex) {
      DialogBoxes.showErrorMessage("Could not be opened!");
      System.err.println(filePath);
    }

    return result;
  }
}
