var path = require('path');
var findIndex = require('lodash.findindex');

var flattenGlob = function(arr){
  var out = [];
  var flat = true;
  for(var i = 0; i < arr.length; i++) {
    if (typeof arr[i] !== 'string') {
      flat = false;
      break;
    }
    out.push(arr[i]);
  }
  if (flat) out.pop(); // last one is a file or specific dir
  return out;
};

var flattenExpansion = function(set) {
  var first = set[0];
  var toCompare = set.slice(1);

  // find index where the diff is
  var idx = findIndex(first, function(v, idx){
    if (typeof v !== 'string') return true;

    var matched = toCompare.every(function(arr){
      var v2 = arr[idx];
      if (typeof v2 !== 'string') return false;
      return v === v2;
    });

    return !matched;
  });

  return first.slice(0, idx);
};

var setToBase = function(set) {
  // normal something/*.js
  if (set.length <= 1) {
    return flattenGlob(set[0]);
  }
  // has expansion
  return flattenExpansion(set);
};

module.exports = function(glob) {
  var cwd = (glob.options && glob.options.cwd) ? glob.options.cwd : process.cwd();
  var set = glob.minimatch.set;
  var baseParts = setToBase(set);
  var basePath = path.normalize(baseParts.join(path.sep))+path.sep;
  return basePath;
};
