(function() {
  var Promise, cwd, formStatePath, fs, log, md5, path, sanitize, toHashName;

  md5 = require("md5");

  path = require("path");

  Promise = require("bluebird");

  sanitize = require("sanitize-filename");

  log = require("../log");

  cwd = require("../cwd");

  fs = require("../util/fs");

  toHashName = function(projectRoot) {
    var hash, name;
    if (!projectRoot) {
      throw new Error("Missing project path");
    }
    if (!path.isAbsolute(projectRoot)) {
      throw new Error("Expected project absolute path, not just a name " + projectRoot);
    }
    name = sanitize(path.basename(projectRoot));
    hash = md5(projectRoot);
    return name + "-" + hash;
  };

  formStatePath = function(projectRoot) {
    return Promise.resolve().then(function() {
      var cypressJsonPath;
      log('making saved state from %s', cwd());
      if (projectRoot) {
        log('for project path %s', projectRoot);
        return projectRoot;
      } else {
        log('missing project path, looking for project here');
        cypressJsonPath = cwd('cypress.json');
        return fs.pathExists(cypressJsonPath).then(function(found) {
          if (found) {
            log('found cypress file %s', cypressJsonPath);
            projectRoot = cwd();
          }
          return projectRoot;
        });
      }
    }).then(function(projectRoot) {
      var fileName, statePath;
      fileName = "state.json";
      if (projectRoot) {
        log("state path for project " + projectRoot);
        statePath = path.join(toHashName(projectRoot), fileName);
      } else {
        log("state path for global mode");
        statePath = path.join("__global__", fileName);
      }
      return statePath;
    });
  };

  module.exports = {
    toHashName: toHashName,
    formStatePath: formStatePath
  };

}).call(this);
