/*
* 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 {PolymerElement, html} from '@polymer/polymer';
import '@polymer/paper-button/paper-button.js';
import { configObj } from '../../shared/constants';

class customTable extends PolymerElement {
  static get template() {
    return html`
    <style>
        table.clockTable {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
            text-align: center;
        }
        .clockTable tr>td:first-child {
          text-align: left;
        }
        .clockTable td {
            border: 1px solid #ddd;
            padding: 8px 12px;
            font-size: 11px;
        }
        .clockTable th {
            background-color: #2196f3;
            color: #fff;
            font-size: 12px;
            border: 1px solid #ddd;
            padding: 8px 12px;
            text-align: center;
        }
        .exportAnchor {
            text-decoration: none;
            color: #fff !important;
        }
        paper-button {
            background-color: #1E88E5;
            color:white;
            height:30px;
            font-size:14px;
        }
        h2 {
          width: 100%;
          margin-bottom: 10px;
          text-align: right;
        }
        #clockheaderwidget {
          display: inline;
          float: right;
        }
        #clocktimestamp {
          display: inline-block;
        }
        #clkexportwidget {
          display: inline-block;
        }
    </style>
    <div id="clockheaderwidget">
    <div id="clocktimestamp">Timestamp: <span>15-03-2021</span></div>
    <div id="clkexportwidget"><h2>
      <paper-button raised noink on-tap="_export" title="Download(csv)">
          <iron-icon icon="swap-vert"></iron-icon>
          <a id="exportData" class="exportAnchor">Download</a>
      </paper-button>
    </h2>
    </div>
    </div>
    <table class="clockTable">
        <thead>
          <tr>
            <template is="dom-repeat" items="{{header_name}}" as="item">
              <template is="dom-if" if={{_compareValues(item)}}>
                <th align='left'>{{_displayunits(item)}}</th>
              </template>
            </template>
          </tr>
        </thead>
        <tbody>
          <template is="dom-repeat" items="{{row_data}}" as="parent">
            <tr>
              <template is="dom-repeat" items="{{_rowWiseData(parent)}}" as='child'>
                <template is="dom-if" if={{_compareValues(child)}}>
                  <td style$="[[_computedStyle(parent, child)]]">{{child}}</td>
                </template>
              </template>
            </tr>
          </template>
        </tbody>
    </table>
    `;
  }

  static get properties() {
    return {
      row_data: {
        type: Array,
        value: [],
        notify: true
      },
      header_name: {
        type: Array,
        value: [],
        notify: true
      }
    };
  }

    _rowWiseData(item) {
        let data = Object.values(item);
        data = data.map(key => key || key === 0 || key === false ? key : '-');
        return data;
    }

    _computedStyle(data, val) {
      if (data && val && data.Live_Value === val && !data.Match)
        return "color : #ffcc99";
      return;
    }

    _compareValues(value) {
      if (value !== 'Match') {
        if (value == 0 && typeof(value) === 'number')
          return '0';
        else if (value !== false && value !== true)
          return value;
      }
      return;
    }

    _displayunits(headername) {
      if(headername === "Target Frequency" || headername === "Actual Frequency")
        return headername + " (MHz)";
      else
        return headername;
    }
  
    _refreshValues() {
      const key = this.dataset.key;
      let currentdatetime = new Date();
      const currentdate = currentdatetime.toDateString();
      const currenttime = currentdatetime.toLocaleTimeString();
      this.$.clocktimestamp.querySelector('span').innerHTML = currentdate + " " + currenttime;
      this.row_data = configObj[`${key}clockdata`].row_data;
      this.header_name = configObj[`${key}clockdata`].header_name;
    }

    _export() {
      if (this.rawItems && this.rawItems.length === 0) {
        return;
      }
      let row = "";
      let csv = "";
      let headers = [];
      const key = this.dataset.key;
      let fileName = "";
      if(key === "rs"){
        let resetname = this.dataset.resettype;
        fileName = resetname + '_reset';
      }else{
        fileName = key + '_clock';
      }
      const table = this.row_data;
      for (let i = 0; i < this.header_name.length; i++) {
        let heading = this.header_name[i];
        if(heading.indexOf(' ') > -1) {
          heading = heading.replace(/ /g, '_');
        }
        headers.push(heading);
        csv += this.header_name[i] + ",";
      }
      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, ';');
              }
              row += table[i][headers[k]] + ',';
            }
          }
        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");
    }

    connectedCallback() {
      super.connectedCallback();
      const key = this.dataset.key;
      let currentdatetime = new Date();
      const currentdate = currentdatetime.toDateString();
      const currenttime = currentdatetime.toLocaleTimeString();
      this.$.clocktimestamp.querySelector('span').innerHTML = currentdate + " " + currenttime;
      this.row_data = configObj[`${key}clockdata`].row_data;
      this.header_name = configObj[`${key}clockdata`].header_name;
      configObj[`${key}clockdata`]["tableref"] = this;
    }
}

customElements.define('custom-table', customTable);
