/**
 * @function save
 * @description This handles saving a cookie in the browser and in memory/headers for server
 */

const cookie = require('cookie');
const _pick = require('lodash/pick');

import { encode } from './encoding';
import { isResWritable } from './util';

const whiteListOpts = [
  'domain',
  'expires',
  'path',
];

export const defaultBrowserOpts = {
  path: '/',
};

export const defaultExpressOpts = {
  path: '/',
};

export const defaultHapiOpts = {
  path: '/',
  isHttpOnly: false,
  isSecure: false,
};

export default (name, val, opt = {}, res) => {
  const options = _pick(opt, whiteListOpts);

  // browser
  if (typeof document !== 'undefined') {
    document.cookie = cookie.serialize(name, encode(val), Object.assign({}, defaultBrowserOpts, options));
  }

  // express
  if (isResWritable(res) && res.cookie) {
    res.cookie(name, encode(val), Object.assign({}, defaultExpressOpts, options));
  }

  // hapi
  if (isResWritable(res) && res.state) {
    res.state(name, encode(val), Object.assign({}, defaultHapiOpts, options));
  }
};

@@ -323,16 +323,67 @@
 'path',%0A
+  // 'secure' ??? would need a mapping for Hapi...%0A
 %5D;%0A%0Aexpo
@@ -419,32 +419,48 @@
  %7B%0A  path: '/',%0A
+  secure: true,%0A
 %7D;%0A%0Aexport const
@@ -496,16 +496,32 @@
 h: '/',%0A
+  secure: true,%0A
 %7D;%0A%0Aexpo
@@ -595,20 +595,19 @@
 Secure: 
-fals
+tru
 e,%0A%7D;%0A%0Ae

make cookies secure by default