export const getBrowser = () => {
  const ua = window.navigator.userAgent.toLowerCase();
  const ver = window.navigator.appVersion.toLowerCase();
  let name = 'unknown';

  if (ua.indexOf('msie') !== -1) {
    if (ver.indexOf('msie 6.') !== -1) {
      name = 'ie6';
    } else if (ver.indexOf('msie 7.') !== -1) {
      name = 'ie7';
    } else if (ver.indexOf('msie 8.') !== -1) {
      name = 'ie8';
    } else if (ver.indexOf('msie 9.') !== -1) {
      name = 'ie9';
    } else if (ver.indexOf('msie 10.') !== -1) {
      name = 'ie10';
    } else {
      name = 'ie';
    }
  } else if (ua.indexOf('trident/7') !== -1) {
    name = 'ie11';
  } else if (ua.indexOf('chrome') !== -1) {
    name = 'chrome';
  } else if (ua.indexOf('safari') !== -1) {
    name = 'safari';
  } else if (ua.indexOf('opera') !== -1) {
    name = 'opera';
  } else if (ua.indexOf('firefox') !== -1) {
    name = 'firefox';
  }
  return name;
};

export const isOldIE = () => {
  const browser = getBrowser();
  if (browser.indexOf('ie') !== -1) {
    if (parseInt(browser.replace(/[^0-9]/g, ''), 10) <= 10) {
      return true;
    }
  }
  return false;
};

export const random = (length) => {
  if (!length) length = 8;
  const quotient = Math.floor(length / 8);
  let remainder = length % 8;
  let txt = '';
  for (let i = 0; i < quotient; i += 1) {
    txt += Math.random().toString(36).slice(-8);
  }
  if (remainder > 0) {
    remainder *= -1;
    txt += Math.random().toString(36).slice(remainder);
  }
  return txt;
};

export class ExpireLocalStorage {
  save(key, jsonData, expirationSec) {
    if (!('localStorage' in window) || !(window.localStorage !== null)) {
      return false;
    }
    const expirationMS = expirationSec * 1000;
    const record = { value: JSON.stringify(jsonData), timestamp: new Date().getTime() + expirationMS };
    localStorage.setItem(key, JSON.stringify(record));
    return jsonData;
  }

  load(key) {
    if (!('localStorage' in window) || !(window.localStorage !== null)) {
      return false;
    }
    const data = localStorage.getItem(key);
    if (!data) {
      return false;
    }
    const record = JSON.parse(data);
    if (!record) { return false; }
    return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
  }
}
