import moment from 'moment';
import _ from 'lodash';
import { createJSEncrypt } from './jsencrypt';
import config from './config';

const { contextPath, pubKey } = config;

export function setCookie(name, value, options = {}) {
  const { path, domain, expires } = options;
  if (name) {
    const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : '';
    const domainSet = domain ? ` domain=${domain};` : '';
    const pathSet = path ? ` path=${path};` : '';
    const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
    document.cookie = `${valueSet}${expireSet}${domainSet};${pathSet}`; // eslint-disable-line
  }
}

export function getCookie(name) {
  const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`);
  const arr = document.cookie.match(reg); // eslint-disable-line
  if (arr) {
    return decodeURIComponent(arr[2]);
  } else {
    return null;
  }
}

export function delCookie(name, { domain, path } = {}) {
  if (getCookie(name)) {
    const domainSet = domain ? ` domain=${domain};` : '';
    const pathSet = path ? ` path=${path};` : '';
    document.cookie = `${name}=; expires=Thu, 01-Jan-70 00:00:01 GMT;${pathSet}${domainSet}`; // eslint-disable-line
  }
}

export function setLocalStorge(key, value) {
  return localStorage.setItem(key, JSON.stringify(value)); // eslint-disable-line
}

export function getLocalStorge(key) {
  return JSON.parse(localStorage.getItem(key)); // eslint-disable-line
}

export function delLocalStorge(key) {
  return localStorage.removeItem(key); // eslint-disable-line
}

export function locationOrigin(withContext = true) {
  return `${location.protocol}//${location.hostname}${location.port ? ':' + location.port : ''}${withContext ? contextPath : ''}`; // eslint-disable-line
}

export function currentPath() {
  let path = location.pathname; // eslint-disable-line
  if (!path) {
    path = '/';
  }
  if (path[0] !== '/') {
    path = `/${path}`;
  }
  if (path.slice(0, contextPath.length) === contextPath) {
    return path.slice(contextPath.length);
  } else {
    return '/';
  }
}

export function fullPath(path) {
  return `${contextPath}${path}`;
}

export function encrypt(text) {
  const jsEncrypt = createJSEncrypt();
  jsEncrypt.setPublicKey(pubKey);
  let out = jsEncrypt.encryptLong(text);
  [out] = out.split('=');
  out = out.replace(/\+/g, '-');
  return out.replace(/\//g, '_');
}

/**
 * @param name {String}
 * @return  {String}
 */
export function queryURL(name) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  // eslint-disable-next-line no-undef
  const r = window ? window.location.search.substr(1).match(reg) : null;
  if (r !== null) return decodeURI(r[2]);
  return null;
}

export function padDigits(number, digits) {
  return new Array(Math.max(digits - String(number).length + 1, 0)).join('0') + number;
}

export function is(obj, type) {
  return (type === 'Null' && obj === null) ||
    (type === 'Undefined' && obj === void 0) || // eslint-disable-line no-void
    (type === 'Number' && isFinite(obj)) || // eslint-disable-line no-restricted-globals
    Object.prototype.toString.call(obj).slice(8, -1) === type;
}

export function makePromise0(thunk) {
  return new Promise((resolve) => {
    thunk(data => resolve(data));
  });
}

export function makePromise1(thunk) {
  return new Promise((resolve, reject) => {
    thunk(err => reject(err), data => resolve(data));
  });
}

export function filterValidParams(params) {
  return _.pickBy(params, _.negate(_.isUndefined));
}

export async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

export async function tryIt(times, cb, delay) {
  let err;
  for (let i = 0; i < times; ++i) {
    try {
      return await cb(); // eslint-disable-line
    } catch (e) {
      err = e;
    }
    if (delay) {
      await sleep(delay); // eslint-disable-line
    }
  }
  if (err) {
    throw err;
  }
}

