"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.deleteCookie = exports.readCookie = exports.writeCookie = void 0;

/**
 * @param {string} name
 * @param {string} value
 * @param {{
 *   maxAge?: number
 *   expires?: Date
 *   secure?: boolean
 *   domain?: string
 * }} opts
 */
const writeCookie = (name, value, {
  maxAge,
  expires,
  secure = false,
  domain
} = {}) => {
  const hostname = globalThis.location && globalThis.location.hostname;
  const cookieData = {
    [name]: value,
    domain: domain || hostname,
    path: '/',
    secure
  };

  if (hostname === 'localhost') {
    cookieData.secure = false;
  }

  if (maxAge) {
    cookieData['max-age'] = Math.floor(maxAge / 1000); // convert to seconds
  } else if (expires) {
    cookieData.expires = expires.toGMTString();
  }

  const cookieString = Object.keys(cookieData).reduce((result, key) => {
    const value = cookieData[key];

    if (typeof value === 'boolean') {
      if (value === true) {
        result.push(key);
      }
    } else {
      result.push("".concat(key, "=").concat(value));
    }

    return result;
  }, []).join(';');
  document.cookie = cookieString;
};

exports.writeCookie = writeCookie;

const readCookie = name => {
  let value = null;
  document.cookie.split(';').find(item => {
    const parts = item.split('=');
    const key = parts[0].trim();

    if (key === name) {
      value = parts[1].trim();
      return true;
    }
  });
  return value;
};

exports.readCookie = readCookie;

const deleteCookie = (item, domain) => writeCookie(item, '', {
  expires: new Date(0),
  domain
});

exports.deleteCookie = deleteCookie;