/*globals window, rJS, domsugar*/
/*jslint indent: 2, nomen: true, maxlen: 80*/

(function (window, rJS, domsugar) {
  "use strict";
  var STATUS_ERROR = 'ui-btn-error',
    STATUS_WARNING = 'ui-btn-warning',
    STATUS_NODATA = 'ui-btn-no-data',
    STATUS_UNHANDLED = 'XXX',
    STATUS_OK = 'ui-btn-ok';

  function checkComputeNodeStatus(compute_node_news_dict) {
    if (compute_node_news_dict.no_data) {
      return STATUS_NODATA;
    }
    if (compute_node_news_dict.text &&
        compute_node_news_dict.text.startsWith("#access")) {
      if (compute_node_news_dict.no_data_since_15_minutes) {
        return STATUS_ERROR;
      }
      if (compute_node_news_dict.no_data_since_5_minutes) {
        return STATUS_WARNING;
      }
      return STATUS_OK;
    }
    return STATUS_UNHANDLED;
  }

  function checkComputePartitionStatus(partition_news_dict_dict) {
    var key,
      error_amount = 0,
      partition_amount = 0;

    for (key in partition_news_dict_dict) {
      if (partition_news_dict_dict.hasOwnProperty(key)) {
        partition_amount += 1;
        if (partition_news_dict_dict.text &&
            partition_news_dict_dict.text.startWith('#error')) {
          error_amount += 1;
        }
      }
    }

    if (partition_amount === 0) {
      return STATUS_NODATA;
    }
    if (0 < error_amount) {
      if (error_amount < partition_amount) {
        return STATUS_WARNING;
      }
      return STATUS_ERROR;
    }
    return STATUS_OK;
  }

  function renderStatus(status_dict) {
    console.log(status_dict);
    var compute_node_status,
      partition_status;

    if (status_dict.compute_node_news_dict) {
      compute_node_status = checkComputeNodeStatus(
        status_dict.compute_node_news_dict
      );
      if ((compute_node_status === STATUS_OK) ||
          (compute_node_status === STATUS_WARNING)) {
        partition_status = STATUS_NODATA;
        if (status_dict.partition_news_dict_dict) {
          // Check if we have info related to the partition
          partition_status = checkComputePartitionStatus(
            status_dict.partition_news_dict_dict
          );
        }
        return [
          domsugar('div', {
            'class': 'ui-block-a ui-bar ui-corner-all first-child ' +
                     'ui-btn ui-btn-icon-left ui-icon-desktop ' +
                     compute_node_status,
            style: 'width:50%',
            text: 'Compute Node'
          }),
          domsugar('div', {
            'class': 'ui-block-c ui-bar ui-corner-all last-child ' +
                     'ui-btn ui-btn-icon-left ui-icon-desktop ' +
                     partition_status,
            style: 'width:50%',
            text: 'Partitions'
          })
        ];
      }
      if (compute_node_status !== STATUS_UNHANDLED) {
        return [
          domsugar('div', {
            'class': 'ui-block-a ui-bar ui-corner-all first-child ' +
                     'ui-btn ui-btn-icon-left ui-icon-desktop ' +
                     compute_node_status,
            style: 'width:50%',
            text: 'Compute Node'
          })
        ];
      }

    }

    // By default, display the full parameters,
    // as it means the gadget does not support the configuration
    // but the parameters may contain usefull stuff for the user
    return [
      'Unsupported',
      domsugar('pre', {text: JSON.stringify(status_dict)})
    ];
  }

  rJS(window)
    .declareAcquiredMethod("jio_get", "jio_get")

    .declareMethod("getContent", function () {
      return {};
    })

    .onLoop(function () {
      var gadget = this;
      console.log('STATUS.onLoop1', gadget.state);
      if (gadget.state.jio_key) {
        return gadget.jio_get(gadget.state.jio_key)
          .push(function (result) {
            console.log('STATUS.onLoop2', result);
            return gadget.changeState({
              compute_node_news_dict:
                JSON.stringify(result.news.compute_node || {}),
              partition_news_dict_dict:
                JSON.stringify(result.news.partition || {})
            });
          });
      }
    }, 300000)

    .declareMethod("render", function (options) {
      console.log('STATUS.render', options);
      return this.changeState({
        compute_node_news_dict: JSON.stringify(options.compute_node || {}),
        partition_news_dict_dict: JSON.stringify(
          options.partition || {}
        ),
        jio_key: options.value,
        reference: options.reference
      });
    })

    .onStateChange(function (modification_dict) {
      console.log('STATUS.onStateChange', modification_dict);
      domsugar(this.element, renderStatus({
        compute_node_news_dict: JSON.parse(this.state.compute_node_news_dict),
        partition_news_dict_dict:
          JSON.parse(this.state.partition_news_dict_dict)
      }));
    });
}(window, rJS, domsugar));