"use strict";

const config = require("config"),
  fs = require("fs"),
  Promise = require("bluebird"),
  picturesPath = config.get("picturesPath").replace(/\/$/, "") + "/";

const stat = function (_path) {
  if (_path.indexOf(picturesPath.replace(/\/$/, "")) == 0) {
    _path = _path.substring(picturesPath.length);
  }

  let path = picturesPath + _path;

  return new Promise(function (resolve, reject) {
    fs.stat(path, function (error, stats) {
      if (error) {
        return reject(error);
      }
      return resolve(stats);
    });
  });
}

const unlink = function (_path) {
  if (_path.indexOf(picturesPath.replace(/\/$/, "")) == 0) {
    _path = _path.substring(picturesPath.length);
  }

  let path = picturesPath + _path;

  return new Promise(function (resolve, reject) {
    fs.unlink(path, function (error) {
      if (error) {
        return reject(error);
      }
      return resolve();
    });
  });
}

const mkdir = function (_path) {
  if (_path.indexOf(picturesPath) == 0) {
    _path = _path.substring(picturesPath.length);
  }

  let parts = _path.split("/"), path;
  
  parts.unshift(picturesPath);
  return Promise.mapSeries(parts, function (part) {
    if (!path) {
      path = picturesPath.replace(/\/$/, "");
    } else {
      path += "/" + part;
    }

    return stat(path).catch(function (error) {
      if (error.code != "ENOENT") {
        throw error;
      }

      return new Promise(function (resolve, reject) {
        fs.mkdir(path, function (error) {
          if (error) {
            return reject(error);
          }

          return resolve();
        });
      });
    });
  });
}

const exists = function(path) {
  return stat(path).then(function() {
    return true;
  }).catch(function() {
    return false;
  });
}

module.exports = {
  stat,
  exists,
  mkdir,
  unlink
};