/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global $, MP_SITE_URL*/
'use strict';

import { GET_UNFILTERED_HOSTS_COUNT_ACTION } from './constants';
import rbac from './rbac';

/*

Get status of the current license details and update header

*/

function calculateDaysLeft(dateString) {
    var dateStringWithoutTZ;
    dateStringWithoutTZ = dateString.split("+", 1);
    let ts = new Date(dateStringWithoutTZ).getTime();
    if (ts < new Date().getTime()) {
        return -1;  // expired
    } else {
        return common.time.calculateNumberOfDays(ts - new Date().getTime());
    }
}

window.calculateDaysLeft = calculateDaysLeft;

var CFE_licenses = (function () {
    var licenseUrl, $wrapperObj, licenseData;
    licenseUrl = MP_SITE_URL + '/licenses/status';
    const unfilteredHostsCountUrl = MP_SITE_URL + '/host/unfilteredCount';
    const hostsCountUrl = MP_SITE_URL + '/host/totalHostsCount';
    $wrapperObj = $('.CFE_LICENSE_STATUS');

    var updateLicenseHeaderDOM = function(data, hostCount) {
      // check for data
      if (!data.licenseGranted) {
        return;
      }

      var daysLeft = calculateDaysLeft(data.expiry);
      var status;
      var formatted = data.expiry.split(' ')[0]; // remove time from date string
      var supportLink = "https://cfengine.com/support/";
      var internalHTML = '';

      if (data.licenseGranted < hostCount) {
        status = 'exceeded';
        $wrapperObj.addClass('exceeded');
      }
      if (data.licenseGranted > 25 && daysLeft < 0) {
        // we ignore expiry date as long as licenses are free25 only
        status = 'expired';
        $wrapperObj.addClass('exceeded');
      }

      if (data.licenseGranted > 25) {
        // NOT free 25
        if (status) {
          if (status === 'expired') {
              internalHTML += '<h3>Your licenses have expired</h3>';
              internalHTML += '<ul class="unstyled">';
              internalHTML += '<li class="margin-bottom">'+ data.licenseGranted +' licenses expired on '+ formatted + '.</li>';
          }
          if (status === 'exceeded') {
              internalHTML += '<h3>You have exceeded your number of licenses</h3>';
              internalHTML += '<ul class="unstyled">';
              internalHTML += '<li class="margin-bottom"><b>'+ hostCount +'</b> hosts are connected to this hub, but it is only licensed to support ' + data.licenseGranted + ' clients.</li>';
          }
          internalHTML += '<li>If you wish to renew or buy more licenses, please <a href="' + supportLink + '" target="_blank">visit our support page</a>.</li>';
          internalHTML += '</ul>';
        } else {
          // within license limit
          internalHTML += '<h3>Your licences are valid for another '+ daysLeft +' days</h3>';
          internalHTML += '<ul class="unstyled">';
          internalHTML += '<li>'+ data.licenseGranted +' licenses will expire on '+ formatted + '.</li>';
          internalHTML += '<li class="margin-top">If you wish to renew or buy more licenses, please <a href="' + supportLink + '" target="_blank">visit our support page</a>.</li>';
          internalHTML += '</ul>';
        }

      } else if (data.licenseGranted) {
        // free25 version
        if (status === 'exceeded') {
          internalHTML += '<h3>You have exceeded your number of licenses</h3>';
          internalHTML += '<ul class="unstyled">';
          internalHTML += '<li class="margin-bottom">CFEngine Enterprise is free for up to 25 hosts, but <b>' + hostCount + '</b> hosts are connected to this hub.</li>';
          internalHTML += '<li>If you wish to renew or buy more licenses, please <a href="' + supportLink + '" target="_blank">contact our team</a>.</li>';
          internalHTML += '</ul>';
        } else {
          // within license limit
          internalHTML += '<h3>CFEngine Enterprise is free for up to 25 hosts</h3>';
          internalHTML += '<ul class="unstyled">';
          internalHTML += '<li>Thanks for using CFEngine Enterprise. If you require more licenses, please <a href="' + supportLink + '" target="_blank">visit our support page</a>.</li>';
          internalHTML += '</ul>';
        }
      }

      $wrapperObj.find('.license_hover_info').html(internalHTML);
      $wrapperObj.find('.detailed-license-count').text(data.licenseGranted);
    }

    var getLicenseData = function(doneCallback, failCallback, alwaysCallback) {
      $.ajax({
              type: 'get',
              url: licenseUrl,
              dataType: 'json',
              cache: false,
              success: function(data) {
                if (data) {
                  updateLicenseHeaderDOM(data);
                }
              },
              error: function(jqXHR, textStatus, errorThrown) {
                return;
              }
          });
    };

    const getUnfilteredHostCountData = async function() {
     await $.ajax({
              type: 'get',
              url: unfilteredHostsCountUrl,
              dataType: 'json',
              cache: false,
              success: function(data) {
                if (data) {
                  $('.detailed-licensed-hosts-count').text(data.licensedHostCount);
                  $('.detailed-hosts-count').text(data.hostCount);
                  $('.detailed-deleted-hosts-count').text(data.deletedHostCount);
                  document.dispatchEvent(new CustomEvent('hostCountUpdated', {detail: data.hostCount}));
                }
              },
              error: function(jqXHR, textStatus, errorThrown) {
                return;
              }
          }).catch(function () {});
    };

    const getHostsCount = async function() {
       // Return 0 hosts if the user does not have permission Query API
       return await $.ajax({
            type: 'get',
            url: hostsCountUrl,
            dataType: 'json',
            cache: false
        }).catch(function () { return { hostCount: 0 }; });
    };

    var getLicenseStatus = function(hostCount) {
      updateLicenseHeaderDOM(licenseData, hostCount);
    };

    var init = async function() {
        if (await rbac.isActionAllowed(GET_UNFILTERED_HOSTS_COUNT_ACTION)) {
            await getUnfilteredHostCountData();
        }
        getLicenseData();
    };

    return {
        init: init,
        getHostsCount: getHostsCount
    };

})();

var CFE_health_header = (function () {
    var connectivityHealthUrl = MP_SITE_URL + '/host/connectivityHealth';
    var $wrapperObj = $('.CFE_HEALTH');

    var getHealthStatus = function(doneCallback, failCallback, alwaysCallback) {
      $.ajax({
          type: 'get',
          url: connectivityHealthUrl,
          dataType: 'json',
          cache: false,
          success: function(data) {

              if (data) {
                  var totalFailed = parseInt(data.totalFailed, 10);
                  var blue = parseInt(data.notRecentlyCollected, 10);
                  var black = parseInt(data.lastAgentRunUnsuccessful, 10);
                  var hostsUsingSameIdentity = parseInt(data.hostsUsingSameIdentity, 10);
                  var hostsUsingSameName = parseInt(data.hostsUsingSameName, 10);
                  var deletedHostsReport = parseInt(data.deletedHostsReport, 10);
                  var hostsNeverCollected = parseInt(data.hostsNeverCollected, 10);
                  var agentNotRunRecently = parseInt(data.agentNotRunRecently, 10);
                  var total = parseInt(data.total, 10);

                  doneCallback(totalFailed); // got host count

                  if (totalFailed === 0) {
                      $wrapperObj.find('.health-count').text('Ok').addClass('badge badge-success');
                  } else {
                      $wrapperObj.find('.health-count').text(totalFailed > 100 ? '99+' : totalFailed).addClass('badge badge-important');
                  }

                  $wrapperObj.find('.connection-error').text(blue);
                  $wrapperObj.find('.agent-error').text(black);
                  $wrapperObj.find('.same-hosts-error').text(hostsUsingSameIdentity);
                  $wrapperObj.find('.same-hosts-name-error').text(hostsUsingSameName);
                  $wrapperObj.find('.deleted-hosts-report-error').text(deletedHostsReport);
                  $wrapperObj.find('.hosts-never-collected').text(hostsNeverCollected);
                  $wrapperObj.find('.agent-not-run-recently').text(agentNotRunRecently);
              }
          },
          error: function(jqXHR, textStatus, errorThrown) {
              return;
          }

      });
  };

    const getTotalHostsCount = () =>
        CFE_licenses.getHostsCount().then(({hostCount: total = null}) => {
            $wrapperObj.find('.total-host-count').text(pluralize('Host', total, true));
            $('.detailed-filtered-hosts-count').text(total);
        })
    
  var init = function(returnHostCount) {
    getHealthStatus(function(count) {
      returnHostCount(count);
    });
    getTotalHostsCount();
  };

  return {
      init: init
  };

})();


$(document).ready(function() {
    CFE_health_header.init(function(hostCount) {
          CFE_licenses.init();
    });
});

window.CFE_licenses = CFE_licenses;
