/*
* 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 { api_url, notificationRef } from './constants.js';
export let calculateBaseAddress = (hexVal, row, col) => {
  let m_r = row << 18;
  let m_c = col << 23;
  return (parseInt(hexVal, 16) + m_r + m_c).toString(16);
};
export let clockTreeData = (data, selpll, refclockObj, clockname) => {
  let pData = {};
  pData.title = data.length > 0 ? data[0].Selected_PLL : '';
  pData.npi_check = false;
  if (selpll && selpll.toLowerCase().indexOf('npi') > -1) pData.npi_check = true;
  pData.items = _.mapObject(_.groupBy(data, 'Absolute_Divider'), clist => clist.map(item => _.omit(item, 'Absolute_Divider')));

  if (clockname === "ps") {
    if (data.length > 0) {
      const selplldata = refclockObj[selpll];
      pData.freq = Math.round(selplldata['refclk'] * selplldata['multiplier'] / selplldata['divider']);
    } else pData.freq = '';
  } else {
    pData.freq = data.length > 0 ? data[0].Target_Frequency : '';
  }

  return pData;
};
export let _setBit = data => {
  let hex = _hex2Bin(data.hexValue);

  let val = _hex2Bin(data.value);

  let m = 0;
  let l = 0;

  if (data.bitWidth.trim()) {
    if (data.bitWidth.indexOf('[') > -1) {
      let bit = data.bitWidth.split('[')[1].split(']')[0];

      if (bit.indexOf(':') > -1) {
        m = bit.split(':')[0];
        l = bit.split(':')[1];
      } else {
        m = bit;
        l = bit;
      }
    } else {
      m = l = data.bitWidth;
    }

    l = parseInt(l);
    m = parseInt(m);
    let len = m - l + 1;

    while (len - hex.length > 0) {
      hex = "0" + hex;
    }

    if (len - hex.length < 0) {
      hex = hex.substring(hex.length - len, hex.length);
    }

    while (parseInt(data.width) - val.length > 0) {
      val = "0" + val;
    }

    if (parseInt(data.width) - val.length < 0) {
      val = hex.substring(0, val);
    }

    for (let i = l, j = 0; i <= m; i++, j++) {
      val = _setCharAt(val, val.length - i - 1, hex[hex.length - j - 1]);
    }

    data.value = parseInt(val, 2).toString(16);
    return data.value;
  }
};
export let _setCharAt = (str, index, chr) => {
  if (index > str.length - 1) return str;
  return str.substring(0, index) + chr + str.substring(index + 1);
};
export let _hex2Bin = n => {
  if (!_checkHex(n)) return "0";
  let binVal = parseInt(n, 16).toString(2);

  while (binVal.length < 32) {
    binVal = "0" + binVal;
  }

  return binVal;
};
export let _checkHex = n => {
  return /(^[0-9A-Fa-f]{1,64}$)|(^0x[0-9A-Fa-f]{1,64}$)/i.test(n);
};
export let downloadConfig = (event, ajaxreq) => {
  const session = JSON.parse(localStorage.getItem('storedUser'));
  ajaxreq.headers['uid'] = session.uid;
  let request = ajaxreq.generateRequest();
  request.completes.then(req => {
    if (req.response.status === "Success") {
      if (!('error' in req.response)) {
        const element = document.createElement('a');
        element.setAttribute('href', `${api_url}files/${req.response.response}`);
        event.target.appendChild(element);
        element.click();
        event.target.removeChild(element);
      } else {
        notificationRef.setAttribute('text', req.response.error);
        notificationRef.open();
      }
    } else if (req.response.status === "Fail") {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
    }
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};
export let editHex = (e, self) => {
  if (e.target.parentNode.querySelector('#hexValue').invalid) {
    notificationRef.setAttribute('text', 'Please provide valid hex value and try again');
    notificationRef.open();
    return;
  }

  const hexValue = e.target.parentNode.querySelector('#hexValue').value;

  if (hexValue) {
    const bitWidth = e.target.dataset.width;

    if (self.urlSearch) {
      const reg_address = e.target.dataset.base_address;
      self.livevaluearray.address = [];
      self.livevaluearray.address.push(reg_address);
      self.selData.access = e.target.dataset.reg_access;
      self.selData.width = e.target.dataset.reg_width;
      self.selData.address = reg_address;
    }

    if (MyAppGlobals.boardstatus) {
      document.querySelector("#pageloader").style.display = "block";
      const session = JSON.parse(localStorage.getItem('storedUser'));
      self.$.livevaluerefresh.headers['uid'] = session.uid;
      const request = self.$.livevaluerefresh.generateRequest();
      request.completes.then(req => {
        const results = req.response.response;

        if (results[0].error) {
          document.querySelector("#pageloader").style.display = "none";
          notificationRef.setAttribute('text', results[0].error);
          notificationRef.open();
        } else {
          self.selData.value = results.length > 0 ? results[0].value : '';
          let selectedData = self.selData;
          selectedData = Object.assign(self.selData, {
            "hexValue": hexValue
          }, {
            "bitWidth": bitWidth
          });
          self.selData.value = _setBit(selectedData);
          let reqBody = {
            "address": self.selData.address,
            "value": "0x" + self.selData.value
          };
          self.writeRegisterarray = [];
          self.writeRegisterarray.push(reqBody);
          writeToRegister(self);
        }
      }, () => {
        if (request.status == 400) redirectToLogin();
      });
    } else {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
    }
  } else {
    notificationRef.setAttribute('text', 'Please write to one register atleast');
    notificationRef.open();
  }
};
export let loadLiveBitfieldsValues = (self, livekey) => {
  if (self.urlSearch) {
    self.livevaluearray.address = [];
    self.livevaluearray.address = _.pluck(self.rawItems, 'base_address');
    self.livevaluearray.address = [...new Set(self.livevaluearray.address)];
  }

  if (MyAppGlobals.boardstatus) {
    document.querySelector("#pageloader").style.display = "block";
    const session = JSON.parse(localStorage.getItem('storedUser'));
    self.$.livevaluerefresh.headers['uid'] = session.uid;
    const request = self.$.livevaluerefresh.generateRequest();
    request.completes.then(req => {
      let results = req.response.response;

      _.each(results, result => {
        let regVal = result.value;
        self.regliveval = regVal;
        regVal = _hex2Bin(regVal);
        let bitValue = "";
        let bitWidth = "";

        if (!result.hasOwnProperty('error')) {
          self.$.registerTableBody.shadowRoot.querySelectorAll('.tr').forEach(element => {
            const items = element.querySelector('.editBtn').dataset;

            if (items.base_address === undefined || result.address === items.base_address) {
              bitWidth = items.width;
              bitValue = calculateBitValue(regVal, bitWidth);
              element.querySelector('.bitliveValue').innerText = parseInt(bitValue, 2).toString(16);
              element.querySelector('.bitliveValue').title = parseInt(bitValue, 2).toString(16);
            }
          });
          self.shadowRoot.querySelector('.liveregistervalue').style.color = "#000";
        } else {
          self.shadowRoot.querySelector('.liveregistervalue').style.color = "#ff0000";
        }
      });

      if (!livekey) self.$.liveRegisterDiv.style.display = "block";
      document.querySelector("#pageloader").style.display = "none";
    }, () => {
      if (request.status == 400) redirectToLogin();
    });
  } else {
    notificationRef.setAttribute('text', 'Please Connect to board and try again');
    notificationRef.open();
  }
};
export let calculateBitValue = (regvalue, width) => {
  width = width.replace('[', '').replace(']', '');
  let msb = 0;
  let lsb = 0;
  if (width.indexOf(":") > -1) width = width.split(':');else width = width.split(',');

  if (width.length > 1) {
    msb = parseInt(width[0]);
    lsb = parseInt(width[1]);
  } else {
    msb = lsb = width[0];
  }

  let widthvalue = regvalue.substring(regvalue.length - msb - 1, regvalue.length - lsb);
  return widthvalue;
};
export let writeAll = (e, self) => {
  if (MyAppGlobals.boardstatus) {
    let flag = 0;
    const updateValues = self.$.registerTableBody.shadowRoot.querySelectorAll('.hexValue');
    const editData = self.$.registerTableBody.shadowRoot.querySelectorAll('.editBtn');

    for (let row of updateValues) {
      if (row.parentNode.querySelector('#hexValue').value) {
        flag = 1;
        break;
      }
    }

    if (flag) {
      document.querySelector("#pageloader").style.display = "block";

      if (self.urlSearch) {
        self.livevaluearray.address = [];

        for (let ele of editData) {
          self.livevaluearray.address.push(ele.dataset.base_address);
        }

        self.livevaluearray.address = [...new Set(self.livevaluearray.address)];
      }

      const session = JSON.parse(localStorage.getItem('storedUser'));
      self.$.livevaluerefresh.headers['uid'] = session.uid;
      const request = self.$.livevaluerefresh.generateRequest();
      request.completes.then(req => {
        const results = req.response.response;

        _.each(results, result => {
          if (result.error) {
            document.querySelector("#pageloader").style.display = "none";
            notificationRef.setAttribute('text', result.error);
            notificationRef.open();
          } else {
            self.writeRegisterarray = [];
            updateValues.forEach((rowValue, i) => {
              const bitWidth = rowValue.parentNode.parentNode.querySelector('.bitWidth').innerText.trim();
              const hexDom = rowValue.parentNode.querySelector('#hexValue');

              if (hexDom.invalid) {
                document.querySelector("#pageloader").style.display = "none";
                notificationRef.setAttribute('text', 'Please provide valid hex value and try again');
                notificationRef.open();
                return;
              } else if (hexDom.value) {
                if (self.urlSearch) {
                  self.selData.access = editData[i].dataset.reg_access;
                  self.selData.width = editData[i].dataset.reg_width;
                  self.selData.address = editData[i].dataset.base_address;
                }

                const index = _.findIndex(self.writeRegisterarray, {
                  address: self.selData.address
                });

                if (index > -1) self.selData.value = self.writeRegisterarray[index].value;else self.selData.value = results.length > 0 ? result.value : '';
                let selectedData = Object.assign({ ...self.selData
                }, {
                  "hexValue": hexDom.value
                }, {
                  'bitWidth': bitWidth
                });
                self.selData.value = _setBit(selectedData);
                let reqBody = {
                  "address": self.selData.address,
                  "value": "0x" + self.selData.value
                };
                if (index > -1) self.writeRegisterarray[index] = reqBody;else self.writeRegisterarray.push(reqBody);
              }
            });
          }
        });

        if (self.writeRegisterarray.length > 0) writeToRegister(self);
      }, () => {
        if (request.status == 400) redirectToLogin();
      });
    } else {
      notificationRef.setAttribute('text', 'Please write to one register atleast');
      notificationRef.open();
    }
  } else {
    notificationRef.setAttribute('text', 'Please Connect to board and try again');
    notificationRef.open();
  }
};
export let writeToRegister = self => {
  const session = JSON.parse(localStorage.getItem('storedUser'));
  self.$.writeRegister.headers['uid'] = session.uid;
  const request = self.$.writeRegister.generateRequest();
  request.completes.then(req => {
    const result = req.response && req.response.response ? req.response.response : [];
    document.querySelector("#pageloader").style.display = "none";

    if (result.length > 0) {
      if (result[0].error) {
        notificationRef.setAttribute('text', result[0].error);
        notificationRef.open();
        return;
      }
    }
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};
export let loadLiveRegValues = (e, self) => {
  let regaddlist = [];
  let resetvalue = [];
  document.querySelector("#pageloader").style.display = "block";
  self.rawItems.forEach(element => {
    regaddlist.push(element.address);
    resetvalue.push(element.reset_value);
  });
  self.livevaluearray.address = regaddlist;
  const session = JSON.parse(localStorage.getItem('storedUser'));
  self.$.moduleRefresh.headers['uid'] = session.uid;
  const request = self.$.moduleRefresh.generateRequest();
  request.completes.then(req => {
    const result = req.response.response;

    if (req.response.status === "Fail") {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
      return;
    }

    if (result.length > 0) {
      _.each(self.rawItems, (element, i) => {
        element.color = "#000";
        element.title = "";

        _.each(result, ele => {
          if (ele.address === element.address) {
            element.live_value = ele.error ? ele.error : ele.value ? '0x' + ele.value : ele.value;
            element.title = ele.error ? ele.error : '';
            if (ele.error) element.color = '#ee3626';else if (element.reset_value && element.live_value.toLowerCase() !== element.reset_value.toLowerCase()) element.color = '#ffcc99';else element.color = '#000';
          }
        });
      });

      self.$.registerTableBody.shadowRoot.querySelectorAll('.tr').forEach((element, k) => {
        const baseadd = element.querySelector('.liveregval').getAttribute("data-address");
        const spanTarget = element.querySelector('.liveregval').querySelector('span').querySelector('input');

        for (let i = 0; i < result.length; i++) {
          if (result[i].address === baseadd) {
            spanTarget.value = result[i].error ? result[i].error : result[i].value ? '0x' + result[i].value : result[i].value;
            let resetV = '';
            let liveV = '';

            if (!result[i].error && result[i].value && resetvalue[i]) {
              resetV = self._hex2Int(resetvalue[i].toLowerCase());
              liveV = self._hex2Int('0x' + result[i].value.toLowerCase());
            }

            spanTarget.setAttribute('title', result[i].error ? result[i].error : result[i].value ? '0x' + result[i].value : result[i].value);

            if (result[i].error) {
              spanTarget.style.color = '#ee3626';
            } else if (resetV === liveV) {
              spanTarget.style.color = '#000';
            } else {
              spanTarget.style.color = '#ffcc99';
            }

            break;
          }
        }
      });
    }

    document.querySelector("#pageloader").style.display = "none";
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};
export let checkKeyUp = e => {
  if (e.currentTarget.value > parseInt(e.currentTarget.getAttribute('max')) && e.keyCode != 46 && e.keyCode != 8) {
    e.preventDefault();
    e.currentTarget.value = parseInt(e.currentTarget.getAttribute('max'));
  } else if (e.currentTarget.value < parseInt(e.currentTarget.getAttribute('min')) && e.keyCode != 46 && e.keyCode != 8) {
    e.preventDefault();
    e.currentTarget.value = parseInt(e.currentTarget.getAttribute('min'));
  }
};
export let refreshLiveValues = (e, self) => {
  const btnref = e.currentTarget;
  document.querySelector("#pageloader").style.display = "block";
  let registerAddressArray = [];
  const baseadd = btnref.parentNode.getAttribute("data-address");
  let index = btnref.parentNode.getAttribute("data-index");
  registerAddressArray.push(baseadd);
  self.livevaluearray.address = registerAddressArray;
  const session = JSON.parse(localStorage.getItem('storedUser'));
  self.$.moduleRefresh.headers['uid'] = session.uid;
  let request = self.$.moduleRefresh.generateRequest();
  request.completes.then(req => {
    if (req.response.status === "Fail") {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
      return;
    }

    const result = req.response.response;
    const spanTarget = btnref.parentNode.querySelector('span').querySelector('input');

    if (result.length > 0) {
      _.each(self.rawItems, (element, k) => {
        let color = element.color === undefined ? "#000" : element.color;
        element.title = "";

        if (element.address === baseadd) {
          index = k;
          element.live_value = result[0].error ? result[0].error : result[0].value ? '0x' + result[0].value : result[0].value;
          element.title = result[0].error ? result[0].error : '';
          if (result[0].error) element.color = '#ee3626';else if (element.reset_value && element.live_value.toLowerCase() !== element.reset_value.toLowerCase()) element.color = '#ffcc99';else element.color = color;
        }
      });

      spanTarget.value = result[0].error ? result[0].error : result[0].value ? '0x' + result[0].value : result[0].value;
      let resetV = '';
      let liveV = '';

      if (!result[0].error && result[0].value && self.rawItems[index].reset_value) {
        resetV = self._hex2Int(self.rawItems[index].reset_value.toLowerCase());
        liveV = self._hex2Int('0x' + result[0].value.toLowerCase());
      }

      spanTarget.setAttribute('title', result[0].error ? result[0].error : result[0].value ? '0x' + result[0].value : result[0].value);

      if (result[0].error) {
        spanTarget.style.color = '#ee3626';
      } else if (resetV === liveV) {
        spanTarget.style.color = '#000';
      } else {
        spanTarget.style.color = '#ffcc99';
      }
    }

    document.querySelector("#pageloader").style.display = "none";
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};
export let handlePaging = (e, self) => {
  const selectitem = e.detail.item.innerText;
  self.pageSize = parseInt(selectitem);

  if (selectitem * self.pageIndex > (self.rawItems && self.rawItems.length)) {
    for (let i = self.pageIndex; self.pageIndex >= 0; self.pageIndex--) {
      if (selectitem * self.pageIndex < (self.rawItems && self.rawItems.length)) {
        break;
      }
    }
  }

  _updatepaginationtext(e, self);
};
export let _updatepaginationtext = (e, self) => {
  if (self.totalItems !== undefined && self.pageIndex !== undefined && self.pageSize !== undefined) {
    const PI = self.pageIndex;
    const TI = self.totalItems;
    const PS = self.pageSize;
    const MPI = parseInt(self.totalItems / self.pageSize);
    let Ptext = "";

    if (PI >= 0 && PI < MPI) {
      Ptext = [PI * PS + 1] + " - " + [PI * PS + PS] + " of " + TI;
    } else {
      Ptext = [PI * PS + 1] + " - " + TI + " of " + TI;
    }

    self.shadowRoot.querySelector('exmg-paper-paging').shadowRoot.querySelector('.page-information').innerHTML = Ptext;
  }
};
export let GetFormattedDate = () => {
  const todayTime = new Date();
  const month = todayTime.getMonth() + 1 < 10 ? '0' + (todayTime.getMonth() + 1) : todayTime.getMonth() + 1;
  const day = todayTime.getDate() < 10 ? '0' + todayTime.getDate() : todayTime.getDate();
  const year = todayTime.getFullYear();
  const formatDate = year + "-" + month + '-' + day;
  return formatDate;
};
export let _checkRange = (addr, range) => {
  let flag = 1;

  _.each(range, val => {
    if (val.indexOf('-')) {
      const data = val.split('-');
      if (parseInt(addr, 16) >= parseInt(data[0], 16) && parseInt(addr, 16) <= parseInt(data[1], 16)) flag = 0;
    }
  });

  if (flag) return true;
  return false;
};
export let redirectToLogin = () => {
  const logoutref = document.querySelector('my-app').shadowRoot.querySelector('app-header-layout').querySelector('app-header').querySelector("#logoutBtn");
  logoutref.click();
};
export let handleErrorResponse = req => {
  document.querySelector("#pageloader").style.display = "none";
  if (_.isString(req)) notificationRef.setAttribute('text', req);else if (req.detail && req.detail.error) notificationRef.setAttribute('text', 'Error: The request failed with status code: 500');else notificationRef.setAttribute('text', 'Error: The request failed with status code: 400');
  notificationRef.open();
};
export let writeAllRegisters = (e, self) => {
  let regaddlist = [];
  let inputErr = true;
  const cregval = e.target.dataset.cregval;

  if (cregval == '') {
    notificationRef.setAttribute('text', 'Please provide valid hex address and try again');
    notificationRef.open();
    return;
  }

  self.$.registerTableBody.shadowRoot.querySelectorAll('.tr').forEach(element => {
    const access_type = element.querySelector('.writeregval').getAttribute("data-accesstype");

    if (access_type !== "ro" && access_type !== "rc" && element.querySelector('paper-input')) {
      if (!cregval && element.querySelector('paper-input').invalid) {
        inputErr = false;
      }

      const baseadd = element.querySelector('.writeregval').getAttribute("data-address");
      const inputVal = element.querySelector('paper-input').value;

      if (inputVal !== "") {
        const obj = {
          "address": baseadd,
          "value": "0x" + inputVal
        };
        regaddlist.push(obj);
      }
    }
  });

  if (cregval) {
    regaddlist = [];

    _.each(self.rawItems, element => {
      if (self.key.indexOf('ddrmc') > -1 || element.access_type && element.access_type !== "ro" && element.access_type !== "rc") {
        const obj = {
          "address": element.address,
          "value": "0x" + cregval
        };
        regaddlist.push(obj);
      }
    });

    if (e.target.previousElementSibling.invalid) inputErr = false;
  }

  self.writeRegisterarray = regaddlist;

  if (regaddlist.length > 0) {
    if (inputErr) {
      document.querySelector("#pageloader").style.display = "block";
      const session = JSON.parse(localStorage.getItem('storedUser'));
      self.$.writeAll.headers['uid'] = session.uid;
      let request = self.$.writeAll.generateRequest();
      let errorPopUp = true;
      request.completes.then(req => {
        if (req.response.status === "Fail") {
          document.querySelector("#pageloader").style.display = "none";
          notificationRef.setAttribute('text', "Please connect to board and try again");
          notificationRef.open();
          return;
        }

        const result = req.response.response;

        if (result.length > 0) {
          self.$.registerTableBody.shadowRoot.querySelectorAll('.tr').forEach(element => {
            const baseadd = element.querySelector('.writeregval').getAttribute("data-address");

            for (let i = 0; i < result.length; i++) {
              if (result[i].address === baseadd) {
                if (result[i].error && errorPopUp) {
                  errorPopUp = false;
                  notificationRef.setAttribute('text', 'One or more addresses have memory write 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 to one register atleast');
    notificationRef.open();
  }
};
export let _startConfiguration = (e, self, tab_name, delay) => {
  let reqBody = [];
  let reqObj = {
    "displayname": tab_name.toUpperCase(),
    "permission": true,
    "delay": delay,
    "status": true,
    "key": tab_name + '_data'
  };
  reqBody.push(reqObj);
  self.$.configperf.url = `${api_url}userperformaceconfiguration/`;
  self.$.configperf.body = reqBody;
  const session = JSON.parse(localStorage.getItem('storedUser'));
  self.$.configperf.headers['uid'] = session.uid;
  self.$.configperf.headers['version'] = session.version;
  let request = self.$.configperf.generateRequest();
  request.completes.then(req => {
    if (req.response.status === "Fail") {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
      return;
    } else {
      self._loadwsdata();
    }
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};
export let _stopConfiguration = (e, self, thread_name, tab_name) => {
  let reqBody = [];
  let reqObj = {
    'threadname': thread_name
  };
  ;
  reqBody.push(reqObj);
  self.$.stopperformance.url = `${api_url}closeplot/`;
  self.$.stopperformance.body = reqBody;
  const session = JSON.parse(localStorage.getItem('storedUser'));
  self.$.stopperformance.headers['uid'] = session.uid;
  self.$.stopperformance.headers['version'] = session.version;
  let request = self.$.stopperformance.generateRequest();
  request.completes.then(req => {
    if (req.response.status === "Fail") {
      notificationRef.setAttribute('text', 'Please Connect to board and try again');
      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
      return;
    } else {
      notificationRef.setAttribute('text', tab_name.toUpperCase() + ' Performance monitor has been stopped.');
      notificationRef.open();
      self.ws.close();
      document.querySelector("#pageloader").style.display = "none";
    }
  }, () => {
    if (request.status == 400) redirectToLogin();
  });
};