(function($) {
  'use strict';

  function formatTimestamp(date) {
    date = date || new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    var displayHours = hours % 12 || 12;
    var displayMinutes = minutes < 10 ? '0' + minutes : minutes;
    return displayHours + ':' + displayMinutes + ' ' + ampm;
  }

  function formatMyDate(date, locale, options) {
    locale = locale || 'en-GB';
    options = options || {};
    var dateObj = date instanceof Date ? date : new Date(date);
    var defaultOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    };
    return new Intl.DateTimeFormat(locale, Object.assign({}, defaultOptions, options)).format(dateObj);
  }

  function generateMessageId(text, type) {
    var hash = 0;
    var str = text + type;
    for (var i = 0; i < str.length; i++) {
      var char = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return 'msg_' + Math.abs(hash);
  }

  function isValidSubscription(endDate, status) {
    if (status === null || status === undefined || status === '' || status === -1) return false;

    var numStatus = Number(status);
    if (numStatus === 2) return false;

    var isActiveOrCancelled = (numStatus === 0 || numStatus === 1);
    if (!endDate) return isActiveOrCancelled;

    try {
      var endUTC = new Date(endDate);
      if (isNaN(endUTC.getTime())) return isActiveOrCancelled;
      return new Date() <= endUTC && isActiveOrCancelled;
    } catch (error) {
      return false;
    }
  }

  function cleanBotText(text) {
    var clean = text;

    var sourcesIdx = clean.indexOf('\n[SOURCES]');
    if (sourcesIdx !== -1) clean = clean.substring(0, sourcesIdx);

    var usageIdx = clean.indexOf('{"usage"');
    var jsonIdx = clean.indexOf('{"type": "references"');
    var answerIdx = clean.indexOf('{"answer"');
    var answerStatusIdx = clean.indexOf('{"answer_status"');

    if (usageIdx !== -1) clean = clean.substring(0, usageIdx);
    else if (jsonIdx !== -1) clean = clean.substring(0, jsonIdx);
    else if (answerIdx !== -1) clean = clean.substring(0, answerIdx);
    else if (answerStatusIdx !== -1) clean = clean.substring(0, answerStatusIdx);

    return clean.trim();
  }

  window.MindwecoHelpers = {
    formatTimestamp: formatTimestamp,
    formatMyDate: formatMyDate,
    generateMessageId: generateMessageId,
    isValidSubscription: isValidSubscription,
    cleanBotText: cleanBotText
  };

})(jQuery);
