import appUtils from "./appUtils";
import Url from "./urlendecode";

function decodeParam(route) {
  if (!route) {
    route = typeof window !== 'undefined' ? window.location.href : '';
  }
  route = Url.decode(route);
  let data = route.split('?');
  let params = {};
  let data2;
  try {
    if (data.length >= 2) {
      data2 = data[1].split('&');
    } else if (data.length == 1) {
      data2 = data[0].split('&');
    } else {
      return {};
    }
  } catch (e) {
    return {};
  }
  data2.forEach(res => {
    res = res.split('=');
    if (res.length >= 2) {
      params[res[0]] = res[1];
    }
  });
  return params;
}

function encodeParam(data) {
  let params = appUtils.deepClone(data);
  let url = '';
  let keys = Object.keys(params);
  keys.forEach(res => {
    if ((params[res] && params[res] !== "") || params[res] === 0) {
      if (typeof (params[res]) !== 'string' && typeof (params[res]) !== 'number') {
        params[res] = 'Object';
      }
      url += "&";
      url += res.toLowerCase();
      url += "=";
      url += encodeURIComponent(params[res]);
    }
  });
  url = url ? url.substring(1) : '';
  return url;
}

export {
  encodeParam,
  decodeParam
};
