/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt'
 * which is part of this source code package
 */

package com.scytl.slogger;

import java.io.File;
import java.io.IOException;

/**
 *
 */
public final class CleanDirProvider {

  public static final String DELETE_ME = "deleteMe";

  public static final String TMP_DIR_NAME = "tmp_";

  private CleanDirProvider() {}

  /**
   * Delete the tmpDir, and all files it contains.
   *
   * @throws IOException
   * @see #getCleanedTmpDir()
   */
  public static void deleteTmpDir() throws IOException {
    File tmpDir = getTmpDir();
    File[] files = tmpDir.listFiles();
    if (files != null) {
      for (File file : files) {
        file.delete();
      }
    }
    tmpDir.delete();
  }

  /**
   * Creates and returns a clean tmpDir. If it already existed it will be whiped.
   *
   * @returns an existing (but clean) instance of the tmpDir
   * @throws IOException
   * @see #getTmpDir()
   */
  public static File getCleanedTmpDir() throws IOException {
    deleteTmpDir();
    File tmpDir = getTmpDir();
    tmpDir.mkdirs();
    return tmpDir;
  }

  /**
   * Provides a File pointer to a named directory in user's $TMP location. The provided pointer may
   * return false if <code>exists()</code> is invoked as this method is not responsible for the
   * creation of the tmp directory.
   *
   * @return an existing instance of the tmpDir (can be dirty)
   * @see #getCleanedTmpDir() to obtain an already created and clean copy of the tmpDir.
   */
  public static File getTmpDir() {
    File f = getMainTmpDir();
    File tmpDir = new File(f, DELETE_ME);
    return tmpDir;
  }

  /**
   * @return
   */
  private static File getMainTmpDir() {
    return new File("target");
  }
}
