package com.capgemini.framework.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Class for common file management.
 **/
public final class FileHelper {
  private static final Logger log = LoggerFactory.getLogger(FileHelper.class);
  private static final char LINE_FEED = 0x000A;

  private FileHelper() {
    // Constructor of helper classes must be private
  }

  /**
   * Check file existence.
   *
   * @param aFilePath File which must be checked
   * @return True when the file exists
   */
  public static boolean fileExist(final String aFilePath) {
    boolean status = true;
    if (aFilePath == null) {
      log.debug("File name is null");
      return false;
    }

    File theFile = new File(aFilePath);
    if (!theFile.exists() || theFile.isDirectory()) {
      log.debug("File does not exist: {}", theFile.getAbsolutePath());
      status = false;
    }

    return status;
  }

  /**
   * Read a text file and findAll its content.
   *
   * @param aSourceFilePath parsed source file path
   * @return string with text file content
   */
  public static String read(final String aSourceFilePath) throws IOException {
    // Check file existence
    if (!fileExist(aSourceFilePath)) {
      throw new FileNotFoundException("File does not exist: " + aSourceFilePath);
    }

    StringBuilder theContent = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new FileReader(aSourceFilePath))) {
      // Browse lines of file
      String theCurrentLine = reader.readLine();
      while (theCurrentLine != null) {
        theContent.append(theCurrentLine);
        theContent.append(LINE_FEED);
        theCurrentLine = reader.readLine();
      }
    }

    // Read file content
    return theContent.toString();
  }
}
