/*
* Copyright (c) 2021 Xilinx, Inc.
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and 
* associated documentation files (the "Software"), to deal in the Software without restriction, including 
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to 
* the following conditions: 
* 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software. 
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* 
*
*
*/
import { html, PolymerElement } from '@polymer/polymer/polymer-element.js';
import './datatable-imports.js';
import { api_url, configObj, notificationRef } from './constants';
import { loadLiveRegValues, refreshLiveValues, handlePaging, redirectToLogin, handleErrorResponse, writeAllRegisters, _updatepaginationtext } from './shared-script.js';
class registerTable extends PolymerElement {
  static get template() {
    return html`
    <style>
            :host {
              display: block;
            }
            paper-card {
              display: block;
              width: 100%;
              margin: auto;
              --paper-card-background-color: white;
            }
            paper-button{
              background-color: #1E88E5;
              color:white;
              height:30px;
              float:right;
              font-size:14px;
            }
            h2 span,
            .buttons {
              width: 100%;
              margin: 20px auto;
            }
            exmg-paper-toolbar .flex {
              @apply --layout-flex;
            }
            #moduleWidget,
            #registerWidget{
              display:none;
            }
            #moduleWidget,
            #registerWidget,
            .regClass > paper-input {
              margin-bottom:15px;
            }
            iron-input {
              width: 100%;
            }
            input {
              font-size: 14px;
              margin: 0px 4px;
              padding: 4px;
              border: 0px solid var(--divider-color);
              width: 100%;
            }
            exmg-paper-toolbar span.interactive-content {
              margin-left: 10px;
              white-space: nowrap;
              overflow: hidden;
              color: rgba(0,0,0,0.38);
              font-size: 14px;
              text-overflow: ellipsis;
              letter-spacing: .005em;
              box-sizing: border-box;
              font-weight: 400;
              cursor: pointer;
              width: 100%;
            }
            .search {
              background: #fff;
              box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
                  0 1px 5px 0 rgba(0, 0, 0, 0.12),
                  0 3px 1px -2px rgba(0, 0, 0, 0.2);
            }
            .search input {
              outline: none;
            }
            exmg-paper-datatable{
              font-size:14px;
            }
            .exportAnchor {
              text-decoration: none;
              color: #fff !important;
            }
            .font-normal {
              font-weight: normal;
            }
            .fontSize {
              font-size: 12px;
            }
            .regClass::after {
              clear: both;
              display: block;
              content: '';
            }
            .regClass {
              display: flex;
              flex-wrap: wrap;
              justify-content: flex-end;
              align-items: center;
              color: #000;
            }
            .mb-0 {
              margin-bottom: 0px;
            }
            .sizeIcon {
              width: 16px;
              margin-right: 2px;
            }
          </style>
          <div id="titleDiv">
            <h2 class="mb-0">
              <span>Register Summary</span>
              <paper-button raised noink on-tap="_loadWidgets" id="backToModule"><iron-icon icon="arrow-back" class="sizeIcon"></iron-icon>Back</paper-button>
              <paper-button raised noink on-tap="_loadLiveRegValues"><iron-icon icon="refresh" class="sizeIcon"></iron-icon>Refresh</paper-button>
              <paper-button raised noink on-tap="_export" title="Download(csv)">
                <iron-icon icon="file-download" class="sizeIcon"></iron-icon>
                <a id="exportData" class="exportAnchor">Download</a>
              </paper-button>
              <paper-button raised noink on-tap="_writetoRegisters" data-key$="multiple">
                <iron-icon icon="create" class="sizeIcon"></iron-icon>Write ALL
              </paper-button>
              <div class="fontSize" id="notetext">
                <b> Note : </b>
                <span class="font-normal">Please unlock {{key}} PCSR before write</span>
              </div>
              <iron-ajax id="writeAll" method="post" url=[[updateRegister]] body={{writeRegisterarray}} handle-as="json" content-type="application/json" last-response="{{handleResponse}}" on-error="_handleErrorResponse"></iron-ajax>
              <iron-ajax id="moduleRefresh" method="post" url=[[getregvalurl]] body={{livevaluearray}} handle-as="json" content-type="application/json" last-response="{{handleResponse}}" on-error="_handleErrorResponse"></iron-ajax>
            </h2>
          </div>
          <div class="regClass">
            <paper-input label="Write to all registers" always-float-label auto-validate pattern="[a-fA-F0-9]*" value={{cregval}} error-message="Invalid hex value">
              <div slot="prefix">0x</div>
            </paper-input>
            <paper-icon-button icon="create" on-tap="_writetoRegisters" data-cregval$={{cregval}}></paper-icon-button>
          </div>
          <paper-card elevation="1">
          <!-- Table Toobar -->
            <exmg-paper-toolbar>
              <div slot="default" class$="[[_computeSearchClasses(isSearch)]]">
                <template is="dom-if" if="[[isSearch]]" restamp="true">
                  <iron-icon icon="exmg-paper-icons:search"></iron-icon>
                  <iron-input bind-value="{{filterValue}}">
                    <input id="searchInput" placeholder="[[placeHolder]]" on-keyup="_handleKeyUp" on-blur="_handleInputBlur">
                  </iron-input>
                </template>
                <template is="dom-if" if="[[!isSearch]]" restamp="true">
                  <iron-icon icon="exmg-paper-icons:search"></iron-icon>
                  <span class="interactive-content" on-tap="_showSearch">[[_getFilterValue(filterValue)]]</span>
                </template>
              </div>
            </exmg-paper-toolbar>
            <!-- DataTable -->
            <exmg-paper-datatable>
              <!-- THead -->
              <exmg-paper-thead sorted="{{sorted}}" sort-direction="{{sortDirection}}">
                <template>
                  <div class="tr">
                    <div title="Module Name" class="th flex-none" id="instanceName" sortable="instance_name" style="width:9%;">
                      <span>Module Name</span>
                    </div>
                    <div title="Name" class="th flex-none" sortable="name" id="regName" style="width:12%">
                      <span>Register Name</span>
                    </div>
                    <div title="Address" class="th flex-none" sortable="address" style="width:9%">
                      <span>Address</span>
                    </div>
                    <div title="Width" class="th flex-none" sortable="width" style="width:6%">
                      <span>Width</span>
                    </div>
                    <div title="Access Type" class="th flex-none" sortable="access_type" style="width:6%">
                      <span>Type</span>
                    </div>
                    <div title="Reset Value" class="th flex-none" sortable="reset_value" style="width:9%">
                      <span>Reset Value</span>
                    </div>
                    <div title="Description" class="th flex-none" sortable="description" id="regDescription" style="width:23%">
                      <span>Description</span>
                    </div>
                    <div title="Live Value" class="th flex-none" style="width:13%">
                      <span>Live Value</span>
                    </div>
                    <div title="Update" class="th flex-none" style="width:13%">
                      <span>Update</span>
                    </div>
                  </div>
                </template>
              </exmg-paper-thead>
              <!-- TBody -->
              <exmg-paper-tbody  id="registerTableBody" items="[[items]]">
                <template>
                  <div class$="[[_computedClass(selected)]]" style="height: 100%;" aria-expand$="[[selected]]">
                    <template is="dom-if" if="[[!item.instance_name]]" restamp="true">
                      <div class="td flex-none regName" data-key$="{{item.key}}" data-register_name$="{{item.name}}" data-index$=[[index]] data-register_width$="{{item.width}}" data-register_address$="{{item.address}}" data-register_access$="{{item.access_type}}" style="width: 15%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                        <span title="[[item.name]]" style="color: #1E88E5;cursor:pointer" on-tap="_loadBitfields">[[item.name]]</span>
                      </div>
                    </template>
                    <template is="dom-if" if="[[item.instance_name]]" restamp="true">
                      <div class="td flex-none" style="width:9%;padding-left:24px;height: auto;padding-top: .5em;padding-bottom: .5em;">
                        <span title="[[item.instance_name]]">[[item.instance_name]]</span>
                      </div>
                      <div class="td flex-none regName" data-key$="{{item.key}}" data-instance_name$="{{item.instance_name}}" data-register_name$="{{item.name}}" data-index$=[[index]] data-register_width$="{{item.width}}" data-register_address$="{{item.address}}" data-register_access$="{{item.access_type}}" style="width:12%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                        <span title="[[item.name]]" style="color: #1E88E5;cursor:pointer" on-tap="_loadBitfields">[[item.name]]</span>
                      </div>
                    </template>
                    <div class="td flex-none" style="width:9%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                      <span title="[[item.address]]">[[item.address]]</span>
                    </div>
                    <div class="td flex-none" style="width:6%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                      <span title="[[item.width]]">[[item.width]]</span>
                    </div>
                    <div class="td flex-none" style="width:6%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                      <span title="[[item.access_type]]">[[item.access_type]]</span>
                    </div>
                    <div class="td flex-none" style="width:9%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                    <span title="[[item.reset_value]]">[[item.reset_value]]</span>
                    </div>
                    <template is="dom-if" if="[[!item.instance_name]]" restamp="true">
                      <div class="td flex-none regDescription" style="width:29%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                        <span style="white-space: normal;" title="[[item.description]]">[[item.description]]</span>
                      </div>
                    </template>
                    <template is="dom-if" if="[[item.instance_name]]" restamp="true">
                      <div class="td flex-none regDescription" style="width:23%;height: auto;padding-top: .5em;padding-bottom: .5em;">
                        <span style="white-space: normal;" title="[[item.description]]">[[item.description]]</span>
                      </div>
                    </template>
                    <div class="td flex-none liveregval" style="width:13%;justify-content: space-between;height: auto;padding-top: .5em;padding-bottom: .5em;" data-index$=[[index]] data-address$="{{item.address}}">
                      <span><input type="text" style$="[[_computedStyle(item.color)]]" title="{{item.live_value}}" value="{{item.live_value}}" disabled/></span>
                      <template is="dom-if" if="[[!item.rc]]">
                        <button style="cursor:pointer;padding:0px;margin-left: 5px;" on-tap="refreshOffset">
                        <iron-icon icon="refresh"></iron-icon></button>
                      </template>
                    </div>
                    <div class="td flex-none writeregval" style="position:relative;width:13%;justify-content: space-between;height: auto;padding-top: .5em;padding-bottom: .5em;" data-address$="{{item.address}}" data-accesstype$="[[item.access_type]]">
                    <template is="dom-if" if="[[_computeResult(item.access_type)]]">
                      <paper-input no-label-float auto-validate pattern="[a-fA-F0-9]*" value={{item.value}} error-message="hexa only!" maxlength="8" style="float:left;width:90%;margin-right: 5px;">
                        <div slot="prefix">0x</div>
                      </paper-input>
                      <paper-icon-button icon="create" on-tap="_writetoSingle" data-key$="single"></paper-icon-button>
                    </template>
                    </div>
                  </div>
                </template>
              </exmg-paper-tbody>
            </exmg-paper-datatable>
            <!-- Table Paging -->
            <exmg-paper-paging total-items={{totalItems}} page-index="{{pageIndex}}" page-size="{{pageSize}}"></exmg-paper-paging>
          </paper-card>
          <!-- Load contacts from json file  -->
          <iron-ajax method="post" id="registerrequest" url=[[url]] on-response="_handleRefreshRes" body={{regreqbody}} handle-as="json" content-type="application/json" last-response="{{rawItems}}" on-error="_handleErrorResponse"></iron-ajax>
          <iron-ajax method="post" id="generateTable" url={{urlSearch}} body={{searchBody}} handle-as="json" content-type="application/json" on-error="_handleErrorResponse"></iron-ajax>
          <!-- Filter items by filter value and return resulting items to the data provider  -->
          <exmg-paper-data-filter raw-items="[[rawItems]]" items="{{filteredItems}}" filter-value="[[filterValue]]" filter-fields="name,address"></exmg-paper-data-filter>
          <!-- Manage sorting and paging  -->
          <exmg-paper-data-helper raw-items="[[filteredItems]]" items="{{items}}" page-index="[[pageIndex]]" page-size="[[pageSize]]" sorted="[[sorted]]" sort-direction="[[sortDirection]]" total-items={{totalItems}}></exmg-paper-data-helper>
          `;
  }
  static get properties() {
    return {
      pageIndex: {
        type: Number,
        value: 0,
      },
      pageSize: {
        type: Number,
        value: 25,
      },
      sorted: {
        type: String,
        value: 'address',
      },
      sortDirection: {
        type: String,
        value: 'ASC',
      },
      filterValue: {
        type: String,
        value: '',
      },
      isSearch: {
        type: Boolean,
        value: false,
      },
      placeHolder: {
        type: String,
        value: 'Search Register by name or address',
      },
      url: {
        type: String,
        value: this.url,
      },
      getregvalurl: {
        type: String,
        value: api_url + 'refreshmodule/',
      },
      updateRegister: {
        type: String,
        value: api_url + 'writetoregister/',
      },
      writeRegisterarray: {
        type: Array,
        value: [],
      },
      moduleName: {
        type: String,
        value: '',
      },
      moduleinstancename: {
        type: String,
        value: '',
      },
      moduleAddress: {
        type: String,
        value: '',
      },
      livevaluearray: {
        type: Object,
        value: { "address": [] },
      },
      selectedData: {
        type: Object,
        value: {}
      },
      seldata: {
        type: String,
        value: ""
      },
      key: {
        type: String,
        value: this.key
      },
      urlSearch: {
        type: String,
        value: ''
      },
      searchBody: {
        type: Object,
        value: ''
      },
      regreqbody: {
        type: Object,
        value: { "instance_name": "", "address": "" }
      }
    };
  }
  _computeResult(item) {
    return !(item.toLowerCase() === "ro" || item.toLowerCase() === "rc" || item === "");
  }
  _computedClass(isSelected) {
    let classes = 'tr item';
    if (isSelected) {
      classes += ' selected';
    }
    return classes;
  }
  _computedStyle(color) {
    let customStyle = 'float: left;border: 0px;background-color: #fff;';
    customStyle += 'color :' + color;
    return customStyle;
  }
  _stopTap(e) {
    // Do something
    e.stopPropagation();
  }
  _getFilterValue(filterValue) {
    return filterValue || this.placeHolder;
  }
  _handleRefreshRes() {
    if (this.dataset.refreshset === 'true') {
      this._loadLiveRegValues();
    } else
      document.querySelector("#pageloader").style.display = "none";
  }
  _export() {
    if (this.rawItems && this.rawItems.length === 0) {
      return;
    }
    let row = "";
    let csv = "";
    let headers = [];
    let fileName = this.moduleinstancename; //this.key.toUpperCase() + '_' +
    const table = this.rawItems;
    const columnHeaders = this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelectorAll('span');
    for (let i = 0; i < columnHeaders.length - 1; i++) {
      let heading = columnHeaders[i].innerText.toLowerCase().trim();
      if (heading.indexOf(' ') > -1) {
        heading = heading.replace(/ /g, '_');
      }
      heading = (heading === "register_name")? "name" : heading;
      heading = (heading === "type")? "access_type" : heading;
      headers.push(heading);
      csv += columnHeaders[i].innerText + ",";
    }
    headers.push('Status');
    csv += 'Status,';
    csv += '\r\n';
    for (let i = 0; i < table.length; i++) {
      row = '';
      for (let k = 0; k < headers.length; k++) {
        if (table[i][headers[k]] != undefined) {
          if (typeof table[i][headers[k]] === 'string' && table[i][headers[k]].indexOf(',') > -1) {
            table[i][headers[k]] = table[i][headers[k]].replace(/,/g, ';');
          }
          if (typeof table[i][headers[k]] === 'string' && table[i][headers[k]].indexOf('\n') > -1) {
            table[i][headers[k]] = table[i][headers[k]].replace(/\n/g, '. ');
          }
          if (headers[k] === 'live_value' && table[i][headers[k]])
            row += table[i][headers[k]] + ',';
          else if (table[i][headers[k]])
            row += table[i][headers[k]] + ',';
          else
            row += '-' + ',';
        } else if (headers[k] === 'Status') {
          if (table[i].reset_value && table[i].live_value) {
            const resetV = this._hex2Int(table[i].reset_value.toLowerCase());
            const liveV = this._hex2Int(table[i].live_value.toLowerCase());
            if (resetV === liveV)
              row += 'Matched' + ',';
            else
              row += 'Not Matched' + ',';
          } else
            row += '-' + ',';
        }
      }
      row = row.slice(0, row.length - 1);
      csv += row + '\r\n';
    }
    const hrefUrl = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    const sender = this.$.exportData;
    sender.setAttribute("href", hrefUrl);
    sender.setAttribute("download", fileName + ".csv");
  }

  _handleKeyUp(e) {
    if (e.keyCode === 27) {
      this._hideSearch();
    }
    this.pageIndex = 0;
    let self = this;
    let eve = "";
    _updatepaginationtext(eve, self);
  }
  _handleInputBlur() {
    this._hideSearch();
  }
  _hideSearch() {
    this.set('isSearch', false);
  }
  _showSearch() {
    this.set('isSearch', true);
    setTimeout(() => this.shadowRoot.querySelector('#searchInput').focus(), 200);
  }
  _computeSearchClasses(isSearch) {
    return isSearch ? 'search' : '';
  }
  _loadWidgets(e) {
    this.parentNode.parentNode.host.parentNode.parentNode.querySelector('module-table').style.display = "block";
    this.parentNode.parentNode.host.remove();
  }
  _loadBitfields(e) {
    let key = this.key;
    if (this.urlSearch)
      key = e.currentTarget.parentNode.dataset.key.toLowerCase();
    key = (key === "am012")?"ps": key;
    const index = e.currentTarget.parentNode.getAttribute("data-index");
    if (!this.urlSearch)
      configObj[key]['RegisterName'] = e.currentTarget.parentNode.getAttribute("data-register_name");
    else {
      configObj[key] = {};
      configObj[key]['RegisterName'] = e.currentTarget.parentNode.getAttribute("data-register_name");
      configObj[key]['moduleinstancename'] = e.currentTarget.parentNode.getAttribute("data-instance_name");
      configObj[key]['moduleaddress'] = e.currentTarget.parentNode.getAttribute("data-register_address");
    }
    const access = e.currentTarget.parentNode.getAttribute("data-register_access");
    const width = e.currentTarget.parentNode.getAttribute("data-register_width");
    this.livevaluearray.address = [];
    this.livevaluearray.address.push(e.currentTarget.parentNode.getAttribute("data-register_address"));
    this.selectedData = {
      value: "",
      access: access,
      width: width,
      address: this.livevaluearray.address[0],
    };
    document.querySelector("#pageloader").style.display = "block";
    import(`./../templates/configuration/${key}-bitfields.js`);
    if (this.parentNode.parentNode.querySelector("#" + key + "bitfieldsDiv")) {
      this.parentNode.parentNode.querySelector("#" + key + "bitfieldsDiv").remove();
    }
    const bitfieldBlock = document.createElement('div');
    bitfieldBlock.setAttribute('id', `${key}bitfieldsDiv`);
    bitfieldBlock.innerHTML = "";
    bitfieldBlock.innerHTML = `<${key}-bitfields></${key}-bitfields>`;
    bitfieldBlock.setAttribute('selData', JSON.stringify(this.selectedData));
    bitfieldBlock.style.display = "block";
    if (this.urlSearch)
      this.parentNode.parentNode.querySelector('#foundDataTable').append(bitfieldBlock);
    else
      this.parentNode.parentNode.append(bitfieldBlock);
    this.style.display = "none";
  }

  _loadLiveRegValues(e) {
    if (MyAppGlobals.boardstatus) {
      loadLiveRegValues(e, this);
    } else {
      document.querySelector("#pageloader").style.display = "none";
      notificationRef.setAttribute('text', "Please connect to board and try again");
      notificationRef.open();
    }
  }

  _hex2Int(hex) {
    let hexString = hex.toString(16);
    if (hexString.length % 2) {
      hexString = '0' + hexString;
    }
    return parseInt(hexString, 16);
  }

  _writetoSingle(e) {
    const btnref = e.currentTarget;
    let registerAddressArray = [];
    const baseadd = btnref.parentNode.getAttribute("data-address");
    const inputVal = btnref.parentNode.querySelector('paper-input').value;
    const inputErr = btnref.parentNode.querySelector('paper-input').invalid;
    if (MyAppGlobals.boardstatus) {
      if (inputVal !== "") {
        if (!inputErr) {
          document.querySelector("#pageloader").style.display = "block";
          const obj = { "address": baseadd, "value": "0x" + inputVal };
          registerAddressArray.push(obj);
          this.writeRegisterarray = registerAddressArray;
          const session = JSON.parse(localStorage.getItem('storedUser'));
          this.$.writeAll.headers['uid'] = session.uid;
          this.$.writeAll.headers['version'] = session.version;
          let request = this.$.writeAll.generateRequest();
          request.completes.then(function (req) {
            const result = req.response.response;
            if (result.length > 0)
              if (result[0].error) {
                notificationRef.setAttribute('text', result[0].error);
                notificationRef.open();
              }
            document.querySelector("#pageloader").style.display = "none";
          }, () => {
            if (request.status == 400)
              redirectToLogin();
          });
        } else {
          notificationRef.setAttribute('text', 'Please provide valid hex address and try again');
          notificationRef.open();
        }
      } else {
        notificationRef.setAttribute('text', 'Please write somevalue and try again');
        notificationRef.open();
      }
    } else {
      notificationRef.setAttribute('text', "Please connect to board and try again");
      notificationRef.open();
    }
  }

  _writetoRegisters(e) {
    if (MyAppGlobals.boardstatus) {
      writeAllRegisters(e,this);
    } else {
      notificationRef.setAttribute('text', "Please connect to board and try again");
      notificationRef.open();
    }
  }

  addBaseaddress(c1, c2) {
    var hexStr = (parseInt(c1, 16) + parseInt(c2, 16)).toString(16);
    while (hexStr.length < 6) { hexStr = '0' + hexStr; } // Zero pad.
    return hexStr;
  }
  refreshOffset(e) {
    if (MyAppGlobals.boardstatus) {
      refreshLiveValues(e, this);
    } else {
      notificationRef.setAttribute('text', "Please connect to board and try again");
      notificationRef.open();
    }
  }

  _handleErrorResponse(req) {
    handleErrorResponse(req);
  }

  ready() {
    super.ready();
    const key = this.key;
    let self = this;
    if (this.key === 'npi' || this.key === 'ddr')
      this.$.notetext.style.display = 'block';
    else
      this.$.notetext.style.display = 'none';
    if (this.dataset.urlsearch && this.dataset.searchbody) {
      this.moduleinstancename = "customModule";
      this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelector('#instanceName').style.display = 'flex';
      this.$.titleDiv.querySelector('h2 span').innerText = "Register Table";
      this.$.backToModule.style.display = 'none';
      this.searchBody = this.dataset.searchbody;
      this.urlSearch = this.dataset.urlsearch;
      const session = JSON.parse(localStorage.getItem('storedUser'));
      this.$.generateTable.headers['uid'] = session.uid;
      this.$.generateTable.headers['version'] = session.version;
      let request = this.$.generateTable.generateRequest();
      request.completes.then((req) => {
        document.querySelector("#pageloader").style.display = "none";
        const results = req.response;
        if (results.length > 0) {
          this.style.display = "block";
          let e = "";
          _updatepaginationtext(e, self);
          this.parentNode.parentNode.querySelector('#errorMsg').style.display = 'none';
        } else {
          this.style.display = "none";
          this.parentNode.parentNode.querySelector('#errorMsg').style.display = 'block';
          return;
        }
        let rawItems = _.pluck(results, "registers");
        results.forEach((element, i) => {
          rawItems[i].instance_name = element.instance_name;
          rawItems[i].base_address = element.base_address;
          rawItems[i].address = '0x' + (parseInt(element.base_address, 16) + parseInt(element.registers.address, 16)).toString(16);
        });
        self.rawItems = [...rawItems];
      }, () => {
        if (request.status == 400)
          redirectToLogin();
      });
    } else {
      this.moduleName = configObj[key]['modulename'];
      this.regreqbody.instance_name = this.moduleinstancename = configObj[key]['moduleinstancename'];
      this.regreqbody.address = this.moduleAddress = configObj[key]['moduleaddress'];
      if (configObj.refresh_status !== "undefined" && configObj.refresh_status == true)
        this.regreqbody.live_value = "";
      this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelector('#regDescription').style.width = "29%";
      this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelector('#regName').style.width = "15%";
      this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelector('#regName').style.paddingLeft = "24px";
      this.shadowRoot.querySelector('exmg-paper-thead').shadowRoot.querySelector('#instanceName').style.display = 'none';
      this.$.titleDiv.querySelector('h2 span').innerText = configObj[key]['moduleinstancename'] + "/Register Table";
      const session = JSON.parse(localStorage.getItem('storedUser'));
      this.$.registerrequest.headers['uid'] = session.uid;
      this.$.registerrequest.headers['version'] = session.version;
      let request = this.$.registerrequest.generateRequest();
      request.completes.then((req) => {
        document.querySelector("#pageloader").style.display = "none";
        let e = "";
        _updatepaginationtext(e, self);
      }, () => {
        if (request.status == 400)
          redirectToLogin();
      });
    }
    const pagingTable = this.shadowRoot.querySelector('exmg-paper-paging').shadowRoot.querySelector('paper-dropdown-menu');
    pagingTable.addEventListener('iron-select', e => { handlePaging(e, this) });
    const paginationbtns = this.shadowRoot.querySelector('exmg-paper-paging').shadowRoot.querySelector('.page-actions').querySelectorAll('paper-icon-button');
    _.each(paginationbtns, (ele, ind) => {
      ele.addEventListener('click', e => {
        _updatepaginationtext(e, self);
      });
    });
  }
}
window.customElements.define('register-table', registerTable);
