/*
* 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 "../../../../node_modules/@polymer/polymer/polymer-element.js";
import { configObj, api_url, notificationRef } from "../../../shared/constants.js";
import { redirectToLogin, handleErrorResponse } from "../../../shared/shared-script.js";

class ClockTable extends PolymerElement {
  static get template() {
    return html`
      <style>
        table.clockTable {
          font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
          border-collapse: collapse;
          width: 100%;
        }
        .clockTable td {
          border: 1px solid #ddd;
          padding: 8px 12px;
        }
        .clockTable th {
          background-color: #2196f3;
          color: #fff;
          border: 1px solid #ddd;
          padding: 8px 12px;
        }
        .mt-15p {
            margin-top: 15px;
        }
      </style>
      <div class="mt-15p" id="psbox">
      </div>
      <iron-ajax id="clockdata" method="post" body="{{clockBody}}" url=[[clockUrl]] on-error="_handleErrorResponse" handle-as="json" content-type="application/json" last-response="{{lastResponse}}"></iron-ajax>
      `;
  }

  static get properties() {
    return {
      row_data: {
        type: Array,
        value: []
      },
      header_name: {
        type: Array,
        value: []
      },
      clockUrl: {
        type: String,
        value: api_url + 'getclockdetails/'
      },
      clockBody: {
        type: Object,
        value: {
          "refresh": true,
          'clock': 'ps'
        }
      }
    };
  }

  _handleErrorResponse(req) {
    handleErrorResponse(req);
  }

  connectedCallback() {
    super.connectedCallback();
    document.querySelector("#pageloader").style.display = "block";

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

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

      if (req.response.error) {
        notificationRef.setAttribute('text', req.response.error);
        notificationRef.open();
        document.querySelector("#pageloader").style.display = "none";
        return;
      }

      const result = req.response.data;
      const data = result.data;
      configObj['refclockObj'] = result.refclk;
      configObj['psclockdata'] = {};
      configObj['psclockdata'] = { ...data
      };
      configObj['psclockdata']['pstreekeys'] = Object.keys(data);
      configObj.psclockdata['refObj'] = [];
      this.row_data = [];
      Object.entries(data).forEach(entry => {
        const [key, values] = entry;
        values.forEach(value => {
          this.row_data.push(value);
        });
      });
      configObj['clockname'] = 'ps';
      configObj['psclockdata']['refclk'] = result.refclk;
      const heading = this.row_data && this.row_data.length > 0 ? Object.keys(this.row_data[0]) : [];
      this.header_name = heading.map(key => key.indexOf('_') > -1 ? key.replace("_", " ") : key);
      configObj['psclockdata']['row_data'] = this.row_data;
      configObj['psclockdata']['header_name'] = this.header_name;
      const element = document.createElement('custom-table');
      element.setAttribute('data-key', 'ps');
      this.$.psbox.appendChild(element);
      import('../custom_table.js');
      document.querySelector("#pageloader").style.display = "none";
    }, () => {
      if (request.status == 400) redirectToLogin();
    });
  }

}

window.customElements.define('clock-table', ClockTable);