'use strict';

/**
 * 获取Cookie数据
 * @param {string|true} key Cookie的Key，为true时将返回所有Cookie
 * @param {{ decode?: boolean, template?: string }} options? 可选
 *
 * getCookie(true);         // => { ...cookies }
 * getCookie('cookie_key'); // => *
 */
function getCookie(key, options) {
  if (!options) options = {};
  var isNoDecode = options.decode === false;
  var template = options.template || document.cookie;
  var decodedCookie = isNoDecode ? template : decodeURIComponent(template);
  var cookieItems = {};
  var cookies = decodedCookie.split(';');
  var isGetAll = key === true;

  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];

    while (cookie.charAt(0) === ' ') {
      cookie = cookie.substring(1);
    }

    var keyVal = cookie.split('=');
    var name = keyVal[0];
    var value = keyVal[1];
    cookieItems[name] = value;
    if (key === name) return cookieItems[key];
  }

  return isGetAll ? cookieItems : '';
}

module.exports = getCookie;
