// taken from http://blog.stevenlevithan.com/archives/parseuri
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
import _ from 'lodash';

const PARSEURI_DEFAULT_OPTIONS = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q: {
    name:   "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?))?((((?:[^?#/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose:  /^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#/]*\.[^?#/.]+(?:[?#]|$)))*\/?)?([^?#/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

export default {
  parseUri : function (str, options) {
    var o = _.defaultsDeep(options || {}, PARSEURI_DEFAULT_OPTIONS);
    var	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) { uri[o.key[i]] = m[i] || ""; }

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
      if ($1) { uri[o.q.name][$1] = $2; }
    });

    return uri;
  },
  mergeUri : function(uriParts) {
    let res = "";
    if(uriParts.protocol) {
      res += uriParts.protocol+":";
    }
    if(uriParts.host) {
      res += "//" + uriParts.host;
    }
    if(uriParts.port) {
      res += ":" + uriParts.port;
    }
    if(uriParts.path) {
      res += uriParts.path;
    }
    if(uriParts.queryKey) {
      res += "?" + _.map(uriParts.queryKey, function(v,k) {
        return k + "=" + v;
      }).join("&");
    }

    return res;
  }
};
