package app.service;

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

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

public class FileOperations {

  private FileOperations() {}

  // TODO: Needs documentation and cleanup
  // TODO: This class needs to be extensively error checked

  public static File openFileWithDialog(Stage stage) throws FileNotFoundException {
    File chosenFile = DialogBoxes.showopenFileWithDialog(stage);

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

    return chosenFile;

  }

  public static File openFolderWithDialog(Stage stage) throws FileNotFoundException {
    File dir = DialogBoxes.showOpenFolderWithDialog(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) {
    File chosenLocation;

    try {
      chosenLocation = DialogBoxes.showSaveFileWithDialog(stage);
    } catch (NoSuchElementException e) {
      return false;
    }

    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 e) {
      DialogBoxes.showErrorMessage("This file could not be opened!");
      System.err.println("[ERROR] File could not be opened: " + filePath.toString());
      System.err.print(e);
    }

    return result;
  }
}
