var fs = require('fs');
var stringutil = require('./stringutil.js');

var VIDEOS_KEY = "videos";
var FOLDERS_KEY = "folders";
var VIDEO_EXT = [ ".mp4", ".avi" ];

function exists(path) {
  try {  
    return fs.existsSync(path);
  } catch (err) {
    return false;
  }
}

function isFolder(path) {
  try {
    var stats = fs.statSync(path);
    return stats.isDirectory();
  } catch (err) {
    return false;
  }
}

function isVideo(path) {
  var i;
  var isVideo = false;
  for (i = 0; i < VIDEO_EXT.length; i++) {
    if (stringutil.endsWith(path, VIDEO_EXT[i])) {
      isVideo = true;
      break;
    }
  }
  return isVideo;
}

function getFolderContents(path) {
  var contents = {};
  contents[VIDEOS_KEY] = [];
  contents[FOLDERS_KEY] = [];
  var files;
  try {
    files = fs.readdirSync(path);
  } catch(err) {
    console.log("ERROR: " + err);
    return contents;
  }
  var i, videos = [], folders = [];
  var filePath;
  for (i = 0; i < files.length; i++) {
    filePath = path + "/" + files[i];
    if (isFolder(filePath) && files[i][0] !== ".") {
      folders.push(files[i]);
    } else if (isVideo(filePath) && files[i][0] !== ".") {
      videos.push(files[i]);
    }
  }
  contents[VIDEOS_KEY] = videos;
  contents[FOLDERS_KEY] = folders;
  return contents;
}

exports.exists = exists;
exports.isFolder = isFolder;
exports.isVideo = isVideo;
exports.getFolderContents = getFolderContents;
exports.VIDEOS_KEY = VIDEOS_KEY;
exports.FOLDERS_KEY = FOLDERS_KEY;
