text: /*
   *Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License"); You may not use
   * this file except in compliance with the License. A copy of the License is located at
   * 
   * http://www.apache.org/licenses/LICENSE-2.0
   * 
   * or in the "license" file accompanying this file. This file is distributed on
   * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or
   * implied. See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import { Component, OnInit, OnDestroy, Output, EventEmitter } from '@angular/core';
  import { Subscription } from 'rxjs/Subscription';
  import { environment } from './../../../../environments/environment';
  import { LoggerService } from '../../../shared/services/logger.service';
  import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
  import { GridOptions } from 'ag-grid';
  import { CommonResponseService } from '../../../shared/services/common-response.service';
  import { UtilsService } from '../../../shared/services/utils.service';
  import * as _ from 'lodash';
  
  @Component({
    selector: 'app-vulnerability-summary-table',
    templateUrl: './vulnerability-summary-table.component.html',
    styleUrls: ['./vulnerability-summary-table.component.css'],
    providers: [CommonResponseService]
  })
  
  export class VulnerabilitySummaryTableComponent implements OnInit, OnDestroy {
  
    selectedAssetGroup: string;
    private errorMessage = 'apiResponseError';
  
    getContextMenuItems: any;
    gridApi: any;
    gridColumnApi: any;
    columns: any = [];
    initComplete = false;
    showtable = false;
  
    gridOptions: GridOptions;
    private subscriptionToAssetGroup: Subscription;
    private dataSubscription: Subscription;
  
    @Output() errorOccurred = new EventEmitter();
  
    errorValue = 0;
  
    constructor(  private commonResponseService: CommonResponseService,
            private assetGroupObservableService: AssetGroupObservableService,
            private logger: LoggerService,
            private utils: UtilsService ) {
  
      this.gridOptions = <GridOptions>{};
      this.gridOptions.columnDefs = [];
  
      this.gridOptions.rowData = [];
          this.getContextMenuItems = function getContextMenuItems(params) {
              const result = [
                'toolPanel',
                'separator',
                'copy',
                'separator',
                'csvExport',
                'separator',
                'autoSizeAll',
                'resetColumns'
              ];
              return result;
          };
  
      this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
        assetGroupName => {
            this.showtable = false;
            this.selectedAssetGroup = assetGroupName;
            setTimeout(() => {
              this.showtable = true;
              this.updateComponent();
            }, 10);
        });
  
    }
  
    ngOnInit() {
      }
  
    updateComponent() {
        this.errorValue = 0;
        this.getData();
    }
  
    getData() {
  
      if (this.dataSubscription) {
        this.dataSubscription.unsubscribe();
      }
  
      const payload = {};
      const queryParam = {
        'ag': this.selectedAssetGroup
      };
      this.errorValue = 0;
      const tableUrl = environment.vulnerabilitySummary.url;
      const tableMethod = environment.vulnerabilitySummary.method;
      this.errorValue = 0;
  
      this.dataSubscription = this.commonResponseService.getData(tableUrl, tableMethod, payload, queryParam).subscribe(
        response => {
  
          try {
            if (this.utils.checkIfAPIReturnedDataIsEmpty(response.distribution)) {
              this.errorOccurred.emit();
              this.errorValue = -1;
              this.errorMessage = 'vulnerabilityMessage';
            } else {
              this.errorValue = 1;
              this.processData(response);
            }
          } catch (e) {
              this.errorOccurred.emit();
              this.errorValue = -1;
              this.errorMessage = 'jsError';
              this.logger.log('error', e);
          }
      },
      error => {
        this.errorOccurred.emit();
        this.errorValue = -1;
        this.errorMessage = 'apiResponseError';
        this.logger.log('error', error);
       });
    }
  
    downloadCsv() {
      this.gridApi.exportDataAsCsv({fileName: 'Vulnerability Summary.csv'});
    }
  
    processData(data) {
     this.columns = [];
     const ObjArr = data.distribution.severityinfo;
     const listofColumns = Object.keys(ObjArr[0]);
     const columns = _.pull(listofColumns, 'severity', 'count');
     this.columns = columns;
  
     let eachObj = {};
     this.gridOptions.columnDefs = [];
     this.gridOptions.rowData = [];
     const objProperties = {
        minWidth: 182,
        maxWidth: 800
      };
  
     for ( let i = 0; i < columns.length; i++) {
      if (columns[i].toLowerCase() === 'severitylevel') {
        eachObj = {
          pinned: 'left',
          lockPosition: true,
          field: columns[i],
          headerName: 'Severity',
          minWidth: 182,
          maxWidth: 800,
          order: 1
        };
      } else if (columns[i].toLowerCase() === 'appcount') {
        eachObj = {
          field: columns[i],
          headerName: 'Applications',
          order: 3
        };
        Object.assign(eachObj, objProperties);
      } else if (columns[i].toLowerCase() === 'uniquevulncount') {
        eachObj = {
          field: columns[i],
          headerName: 'Unique Vulnerabilities',
          order: 2,
          minWidth: 182
        };
        Object.assign(eachObj, objProperties);
      } else if (columns[i].toLowerCase() === 'hostcount') {
        eachObj = {
          field: columns[i],
          headerName: 'Servers',
          order: 4
        };
        Object.assign(eachObj, objProperties);
      } else if (columns[i].toLowerCase() === 'vulninstancecount') {
        eachObj = {
          field: columns[i],
          headerName: 'Vulnerability Instances',
          order: 5,
          minWidth: 182
        };
        Object.assign(eachObj, objProperties);
      } else {
        eachObj = {
            field: columns[i],
            headerName: columns[i],
            minWidth: 182,
            maxWidth: 800
          };
      }
  
      this.gridOptions.columnDefs.push(eachObj);
      }
      // sortobject as per 'order' property set.
      this.gridOptions.columnDefs.sort((a, b) => {
        return a['order'] - b['order'];
      });
  
      // get sum of each column
      let sum_vulnerability = 0;
      let sum_applications = 0;
      let sum_servers = 0;
      let sum_instances = 0;
  
      data.distribution.severityinfo.reduce(function(total, currentValue) {
        if (currentValue['uniqueVulnCount']) {
          sum_vulnerability = sum_vulnerability + currentValue['uniqueVulnCount'];
        }
        if (currentValue['appCount']) {
          sum_applications = sum_applications + currentValue['appCount'];
        }
        if (currentValue['hostCount']) {
          sum_servers = sum_servers + currentValue['hostCount'];
        }
        if (currentValue['vulnInstanceCount']) {
          sum_instances = sum_instances + currentValue['vulnInstanceCount'];
        }
      }, []);
  
      const updateRowData = [];
      // delete rows which are not required to display.
      for ( let j = 0; j < data.distribution.severityinfo.length; j++) {
        delete data.distribution.severityinfo[j].severity;
        delete data.distribution.severityinfo[j].count;
        updateRowData.push(data.distribution.severityinfo[j]);
      }
      this.gridOptions.rowData = updateRowData;
      this.gridOptions.getRowStyle = function(params) {
        if (params.data.severitylevel === 'TOTAL') {
          return { 'font-weight': 700 };
        }
      };
      if (this.gridApi) {
        this.gridApi.setColumnDefs(this.gridOptions.columnDefs);
        this.gridApi.setRowData(this.gridOptions.rowData);
        this.onresize();
      }
    }
  
    onresize() {
      if (this.columns.length < 6 && this.columns.length > 0) {
        setTimeout(() => {
          this.gridApi.sizeColumnsToFit();
        }, 3);
      } else {
        this.autoSizeAll();
      }
    }
  
    onGridReady(params) {
      this.gridApi = params.api;
      this.gridColumnApi = params.columnApi;
    }
  
    autoSizeAll() {
      const allColumnIds = [];
      if (this.gridColumnApi) {
        this.gridColumnApi.getAllColumns().forEach(function(column) {
          allColumnIds.push(column.colId);
        });
        this.gridColumnApi.autoSizeColumns(allColumnIds);
      }
    }
  
    ngOnDestroy() {
      try {
        if (this.subscriptionToAssetGroup) {
          this.subscriptionToAssetGroup.unsubscribe();
        }
        if (this.dataSubscription) {
          this.dataSubscription.unsubscribe();
        }
      } catch (error) {
        this.logger.log('error', '--- Error while unsubscribing ---');
      }
    }
  
  }
  