"use strict";

/**
 * Licensed Materials - Property of IBM
 * IBM Cognos Products: admin
 * Copyright IBM Corp. 2017,2018
 * US Government Users Restricted Rights -
 * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */
define(['bi/admin/common/slideout/BasePane', 'bi/commons/ui/properties/PropertyUIControl', 'bi/admin/nls/StringResource', 'bi/admin/system/services/TopicsListController'], function (BasePane, PropertyUIControl, StringResource, TopicsListController) {
  'use strict'; //NOSONAR: meant to be strict

  var LoggingConfigurationPane = BasePane.extend({
    currentTopic: {
      topicName: '',
      topicType: ''
    },
    init: function init(options) {
      LoggingConfigurationPane.inherited('init', this, arguments);
      $.extend(this, options);
      this.topicsController = this._getNewTopicsListController({
        glassContext: this.glassContext
      });
    },
    _getNewTopicsListController: function _getNewTopicsListController(options) {
      return new TopicsListController(options);
    },
    renderBody: function renderBody($body) {
      this.$el.addClass("diagnosticLogging");
      return this.topicsController._getCurrentTopic().then(function (currentTopic) {
        this.currentTopic = this._renderCurrentTopic(currentTopic);
        var aControls = [];
        this.logType = {
          'type': 'SingleLineValue',
          'name': 'logType',
          'label': StringResource.get('logType'),
          'value': StringResource.get(this.currentTopic.topicName)
        };
        this.logDetails = {
          'type': 'TextArea',
          'label': StringResource.get(this.currentTopic.topicName + '_Description'),
          'value': '',
          'editable': false,
          'multiline': false,
          'name': 'logDetails',
          'indent': 2
        };
        aControls.push(this.logType);
        aControls.push(this.logDetails);
        var tabItems = [{
          'name': StringResource.get('topics'),
          'module': 'bi/admin/system/BuiltinTopicTab',
          'parentView': this.slideout,
          'onSelectCallback': this.getCurrentSelection.bind(this),
          'currentHomeValue': this.currentTopic
        }, {
          'name': StringResource.get('addOnTopics'),
          'module': 'bi/admin/system/CustomTopicTab',
          'parentView': this.slideout,
          'onSelectCallback': this.getCurrentSelection.bind(this),
          'currentHomeValue': this.currentTopic
        }];
        aControls.push({
          'type': 'TabControl',
          'items': tabItems,
          'name': 'topicTab'
        });
        aControls.push({
          'type': 'Footer',
          'name': 'topicsFooter',
          'items': [{
            'type': 'Button',
            'label': StringResource.get('apply'),
            'primary': true,
            'onSelect': this.applyLoggingConfiguration.bind(this),
            'name': 'applyButton'
          }, {
            'type': 'Button',
            'label': StringResource.get('reset'),
            'primary': false,
            'onSelect': this._resetToDefault.bind(this),
            'name': 'resetButton'
          }]
        });
        this._oPropertyUIControl = this._newPropertyUIControl({
          'glassContext': this.glassContext,
          'el': $body,
          'items': aControls
        });
        return this._oPropertyUIControl.render().then(function () {
          this._disableApplyButton();
        }.bind(this));
      }.bind(this));
    },
    _newPropertyUIControl: function _newPropertyUIControl(options) {
      return new PropertyUIControl(options);
    },
    _renderCurrentTopic: function _renderCurrentTopic(topicJson) {
      var result = {
        topicName: '',
        topicType: ''
      };
      var topicObjArray = topicJson['logsEnabled'];

      if (topicObjArray.length === 0) {
        result.topicName = 'DEFAULT';
        result.topicType = 'BUILTIN';
      } else {
        for (var i = topicObjArray.length - 1; i >= 0; i--) {
          if (topicObjArray[i]['topicName'] && topicObjArray[i]['topicType']) {
            result.topicName = topicObjArray[i]['topicName'];
            result.topicType = topicObjArray[i]['topicType'];
            break;
          } else {
            result.topicName = topicObjArray[i]['topicName'];
          }
        }
      }

      return result;
    },
    _updateSelectedLogDetails: function _updateSelectedLogDetails() {
      // only show selected topic label if the selected topic is in the tab that is active
      var tabType = this._oPropertyUIControl.getProperty('topicTab')._selectedTabObject.item.module.includes('Builtin') ? 'BUILTIN' : 'CUSTOM';

      if (this.currentSelection && tabType === this.currentSelection.topicType) {
        this._setLabelValue(this._oPropertyUIControl.getProperty('selectedLogDetails'), this._getSelectedLogTopicLabel());
      } else {
        this._setLabelValue(this._oPropertyUIControl.getProperty('selectedLogDetails'), '');
      }
    },
    _setLabelValue: function _setLabelValue(UIProperty, text) {
      var $label = UIProperty.getPropertyNode().find('label');

      if ($label.length > 0) {
        $label.text(text);
      }

      UIProperty.processEllipses();
    },
    getCurrentSelection: function getCurrentSelection(selection) {
      this.currentSelection = selection;
      this.checkApplyButton();

      this._oPropertyUIControl.getProperty('logType').setValue(StringResource.get(this.currentSelection.topicName));

      this._setLabelValue(this._oPropertyUIControl.getProperty('logDetails'), StringResource.get(this.currentSelection.topicName + '_Description')); //clear the other tab


      var topicTabs = this._oPropertyUIControl.getProperty('topicTab')._tabs;

      for (var i = 0; i < topicTabs.length; i++) {
        if (topicTabs[i].item.name === StringResource.get('topics') && this.currentSelection.topicType === 'CUSTOM' && !_.isUndefined(topicTabs[i].tabContent)) {
          topicTabs[i].tabContent._listControl._clearRows();
        }

        if (topicTabs[i].item.name === StringResource.get('addOnTopics') && this.currentSelection.topicType === 'BUILTIN' && !_.isUndefined(topicTabs[i].tabContent)) {
          topicTabs[i].tabContent._listControl._clearRows();
        }
      }
    },
    checkApplyButton: function checkApplyButton() {
      return this.topicsController._getCurrentTopic().then(function (data) {
        var currentActiveTopic = this._renderCurrentTopic(data);

        if (currentActiveTopic.topicName !== this.currentSelection.topicName) {
          this._enableApplyButton();
        } else {
          this._disableApplyButton();
        }
      }.bind(this));
    },
    applyLoggingConfiguration: function applyLoggingConfiguration() {
      this.currentTopic = this.currentSelection;
      var loggingSettings;
      var loggerList = [];
      loggerList.push(this.currentTopic);
      loggingSettings = {
        '_meta': {
          'type': 'glugLoggingConfiguration',
          'version': '0.0.1'
        },
        'defaultLevel': 'ERROR',
        'defaultSessionLevel': 'DEBUG',
        'logsEnabled': loggerList
      };
      return this.topicsController._updateLoggingConfiguration(loggingSettings).then(function () {
        this._disableApplyButton();

        return this.glassContext.appController.showToast(StringResource.get('topicEnableSuccessMsg', {
          'topicName': StringResource.get(this.currentTopic.topicName)
        }), {
          'type': 'success'
        });
      }.bind(this));
    },
    _resetToDefault: function _resetToDefault() {
      this.currentSelection = {
        topicName: 'DEFAULT',
        topicType: 'BUILTIN'
      };
      return this.applyLoggingConfiguration().then(function () {
        this._oPropertyUIControl.getProperty('logType').setValue(StringResource.get(this.currentSelection.topicName));

        this._setLabelValue(this._oPropertyUIControl.getProperty('logDetails'), StringResource.get(this.currentSelection.topicName + '_Description'));

        var topicTabs = this._oPropertyUIControl.getProperty('topicTab')._tabs;

        this._oPropertyUIControl.getProperty('topicTab').selectTabByName(StringResource.get('topics'));

        var topicRows = this.$body.find('.listControl tr');

        for (var j = 1; j < topicRows.length; j++) {
          if (topicRows[j].childNodes[1].firstChild.innerText === StringResource.get(this.currentSelection.topicName)) {
            this._oPropertyUIControl.getProperty('topicTab')._selectedTabObject.tabContent._listControl._selectRow(topicRows[j]);
          } else {
            $(topicRows[j]).removeClass('selected');
          }
        }

        for (var i = 0; i < topicTabs.length; i++) {
          if (topicTabs[i].item.name === StringResource.get('addOnTopics')) {
            topicTabs[i].tabContent._listControl._clearRows();
          }
        }
      }.bind(this));
    },
    _getApplyButton: function _getApplyButton() {
      var footerSection = this._oPropertyUIControl.getProperty('topicsFooter');

      return footerSection._oPropertyUIControl.getProperty('applyButton');
    },
    _disableApplyButton: function _disableApplyButton() {
      this._getApplyButton().disable();
    },
    _enableApplyButton: function _enableApplyButton() {
      this._getApplyButton().enable();
    }
  });
  return LoggingConfigurationPane;
});