var debug = require('debug')('utils');

var fs = require('fs');
var path = require('path');

var checkLocalePath = function(basePath, value, lang) {
  var localePath = path.join(basePath, 'locales', lang, value);

  try {
    var localeStat = fs.statSync(localePath);
    if (localeStat.isFile()) {
      debug("Find locale resource: " + localePath);
      return localePath;
    }
  } catch (err) {
    if (err.code === 'ENOENT' && err.syscall === 'stat') {
      var langs = lang.split('-');
      if (langs.length > 1) {
        langs.pop();
        return checkLocalePath(basePath, value, langs.join('-'))
      } else {
        debug("Fail to Find the locale resource: " + path.join(basePath, value));
        return path.join(basePath, value);
      }
    }
  }
};

var getFileSize = function(filePath) {
  try {
    var stat = fs.statSync(filePath);
    if (stat.isFile()) {
      return stat["size"];
    }
  } catch (e) {
    debug(e);
  }

  return 0;
};

var isLocalFile = function(filePath) {
  try {
    var stat = fs.statSync(filePath);
    if (stat.isFile())
      return true;
  } catch (e) {
    debug(e);
  }

  return false;
};

module.exports.checkLocalePath = checkLocalePath;
module.exports.getFileSize = getFileSize;
module.exports.isLocalFile = isLocalFile;