/*
* 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 './shared-styles.js';
import "../node_modules/@polymer/paper-button/paper-button.js";
import "../node_modules/@polymer/paper-input/paper-input.js";
import "../node_modules/@polymer/iron-ajax/iron-ajax.js";
import "../node_modules/@polymer/paper-toggle-button/paper-toggle-button.js";
import "../node_modules/@polymer/paper-checkbox/paper-checkbox.js";
import { configObj, api_url, notificationRef } from "./shared/constants.js";
import { redirectToLogin, handleErrorResponse } from "./shared/shared-script.js";

class Userconfiguration extends PolymerElement {
  static get template() {
    return html`
        <style include="shared-styles">
            :host {
                display: block;
                height: 100%;
            }
            .configfooter {
                margin-top: 15px;
                text-align: right;
            }
            .cancelBtn,
            .saveBtn {
                padding: 4px 8px;
                background-color: #1E88E5;
                color: #fff;
                font-size: 14px;
                font-weight: bold;
                text-align: center;
            }
            .w-7 {
                width: 7em;
            }
            .performanceconf {
                overflow-y: auto;
                max-height: 66vh;
            }
            .contentBlk {
                padding: 15px;
                display:flex;
                flex-wrap: wrap;
            }
            .w-100 {
                width: 100%;
            }
            .mb-8 {
                margin-bottom: .5em;
            }
            .eachRow {
                width: 12vw;
            }
            .separator {
                width: 1vw;
                margin: 0px 3px;
                font-weight: bold;
            }
            .dflex {
                display: flex;
            }
            .w-10 {
                width: 10em;
            }
            paper-dropdown-menu {
                --paper-input-container-label: {
                    font-size: 20px;
                }
            }
            paper-dropdown-menu {
                --paper-dropdown-menu: {
                    width : 200px;
                }
            }
            .toggleBtn {
                margin: 8px 0px;
            }
        </style>
        <h2>{{heading}}</h2>
        <div class="performanceconf">
            <template is="dom-if" if={{connected}}>
                <div class="w-100">
                    <paper-input autofocus label="Board Name/IP Address" value={{hostAddr}} always-float-label auto-validate>
                    </paper-input>
                    <paper-input label="Port" value={{portNum}} always-float-label auto-validate pattern="[0-9]*">
                    </paper-input>
                </div>
            </template>
            <template is="dom-if" if={{perfConfig}}>
                <div class="contentBlk">
                    <template is="dom-repeat" items={{configData}}>
                        <div class="w-10 mb-8">
                            <paper-checkbox checked={{item.permission}}>{{item.displayname}}</paper-checkbox>
                        </div>
                    </template>
                </div>
            </template>
            <template is="dom-if" if={{board}}>
                <!-- <div class="mb-8 dflex"><div class="eachRow">Board Name/IP Address</div><div class="separator">:</div><div>{{boardname}}</div></div>
                <div class="mb-8 dflex"><div class="eachRow">Port</div><div class="separator">:</div><div>{{portNum}}</div></div> -->
                <!-- <div class="mb-8 dflex"><div class="eachRow">DNA</div><div class="separator">:</div><div>{{devicedna}}</div></div> -->
                <!-- <div class="mb-8 dflex"><div class="eachRow">Daughter Card</div><div class="separator">:</div><div>--</div></div> -->
                <div class="mb-8 dflex"><div class="eachRow">Ref Clock</div><div class="separator">:</div><div>{{refclk}} MHz</div></div>
                <div class="mb-8 dflex"><div class="toggleBtn"><paper-toggle-button id="freadCheck" checked={{freadStatus}} on-change="_freadChanged" noink>Force Memory Read</paper-toggle-button></div></div>
            </template>
            <template is="dom-if" if={{databaseconfig}}>
                <paper-dropdown-menu always-float-label label="Database" class="searchValue" id="selectedVersion">
                    <paper-listbox slot="dropdown-content" class="dropdown-content" selected="{{versionindex}}">
                        <template is="dom-repeat" items={{databaselist}}>
                            <paper-item>[[item]]</paper-item>
                        </template>
                    </paper-listbox>
                </paper-dropdown-menu>
            </template>
        </div>
        <div class="configfooter">
            <paper-button class="saveBtn" hidden={{!perfConfig}} on-tap="_saveConfig" raised noink>Save</paper-button>
            <paper-button class="saveBtn" hidden={{!databaseconfig}} on-tap="_updateDatabase" raised noink>Update</paper-button>
            <paper-button class="saveBtn" hidden={{!connected}} on-tap="_connectCall" raised noink>Connect</paper-button>
            <paper-button class="cancelBtn" dialog-dismiss raised noink>Close</paper-button>
        </div>
        <iron-ajax id="configperf" method="post" url=[[configurl]] body={{configData}} handle-as="json" content-type="application/json" last-response="{{lastResponse}}" on-error="_handleErrorResponse"></iron-ajax>
        <iron-ajax id="setmemaccessxhr" method="GET" url=[[memaccessurl]] handle-as="json" content-type="application/json"></iron-ajax>
        `;
  }

  static get properties() {
    return {
      configurl: {
        type: String,
        value: api_url + 'userperformaceconfiguration/'
      },
      memaccessurl: {
        type: String,
        value: ''
      },
      heading: {
        type: String,
        value: ''
      },
      connected: {
        type: Boolean,
        value: false
      },
      board: {
        type: Boolean,
        value: false
      },
      perfConfig: {
        type: Boolean,
        value: false
      },
      databaseconfig: {
        type: Boolean,
        value: false
      },
      databaselist: {
        type: Array,
        value: []
      },
      versionindex: {
        type: Number,
        value: 0
      },
      configData: {
        type: Array,
        value: [{
          "displayname": "PMC",
          "permission": false,
          "status": true,
          "key": 'pmc_data'
        }, {
          "displayname": "LPD",
          "permission": false,
          "status": true,
          "key": 'lpd_data'
        }, {
          "displayname": "FPD",
          "permission": false,
          "status": true,
          "key": 'fpd_data'
        }, {
          "displayname": "CPM",
          "permission": false,
          "status": true,
          "key": 'cpm_data'
        }, {
          "displayname": "DDRMC0",
          "permission": false,
          "status": true,
          "key": 'ddr0_data'
        }, {
          "displayname": "DDRMC1",
          "permission": false,
          "status": true,
          "key": 'ddrmc1_data'
        }, {
          "displayname": "DDRMC2",
          "permission": false,
          "status": true,
          "key": 'ddrmc2_data'
        }, {
          "displayname": "DDRMC3",
          "permission": false,
          "status": true,
          "key": 'ddrmc3_data'
        }, {
          "displayname": "NoC",
          "permission": false,
          "status": true,
          "key": 'noc_data'
        }, {
          "displayname": "AI Engine",
          "permission": false,
          "status": true,
          "key": 'aiengine_data'
        }, {
          "displayname": "PL",
          "permission": false,
          "status": true,
          "key": 'pl_data'
        }]
      },
      freadStatus: {
        type: Boolean,
        value: false
      }
    };
  }

  _connectCall() {
    const urlIndex = this.hostAddr.indexOf('.xilinx.com');
    let hostAddr = this.hostAddr;

    if (urlIndex > -1) {
      hostAddr = this.hostAddr.replace('.xilinx.com', '');
    }

    MyAppGlobals.appRef.callnetworkConnectBtn(hostAddr, this.portNum);
  }

  _saveConfig() {
    const session = JSON.parse(localStorage.getItem('storedUser'));
    this.$.configperf.headers['uid'] = session.uid;
    let self = this;

    const checkTrue = _.findIndex(self.configData, {
      "permission": true
    });

    if (checkTrue < 0) {
      notificationRef.setAttribute('text', 'Please select atleast one');
      notificationRef.open();
      return;
    }

    self.parentNode.parentNode.parentNode.querySelector('#configurationmodal').close();
    document.querySelector("#pageloader").style.display = "block";
    const dc = {
      "displayname": "DC",
      "permission": true,
      "status": true,
      "key": 'dc_data'
    }; // const ddrmc0_eff = { "displayname": "DDRMC0_Efficiency", "permission": true, "status": true, "key": 'ddrmc0_efficiency' };
    // const ddrmc1_eff = { "displayname": "DDRMC1_Efficiency", "permission": true, "status": true, "key": 'ddrmc1_efficiency' };
    // const ddrmc2_eff = { "displayname": "DDRMC2_Efficiency", "permission": true, "status": true, "key": 'ddrmc2_efficiency' };
    // const ddrmc3_eff = { "displayname": "DDRMC3_Efficiency", "permission": true, "status": true, "key": 'ddrmc3_efficiency' };

    const indexFind = _.findIndex(self.configData, {
      "displayname": "DDRMC0",
      "permission": true
    });

    const indexFindDC = _.findIndex(self.configData, {
      "displayname": "DC"
    }); // const ddr1indexFind = _.findIndex(self.configData, {"displayname": "DDRMC1", "permission": true});
    // const indexFindDDRMC1 = _.findIndex(self.configData, {"displayname": "DDRMC1 Efficiency"});
    // const ddr2indexFind = _.findIndex(self.configData, {"displayname": "DDRMC2", "permission": true});
    // const indexFindDDRMC2 = _.findIndex(self.configData, {"displayname": "DDRMC2 Efficiency"});
    // const ddr3indexFind = _.findIndex(self.configData, {"displayname": "DDRMC3", "permission": true});
    // const indexFindDDRMC3 = _.findIndex(self.configData, {"displayname": "DDRMC3 Efficiency"});


    if (indexFindDC > -1) self.configData.splice(indexFindDC, 1);

    if (indexFind > -1) {
      self.configData.push(dc); //self.configData.push(ddrmc0_eff);
    } // if (indexFindDDRMC1 > -1)
    //     self.configData.splice(indexFindDDRMC1, 1);
    // if (ddr1indexFind > -1){
    //     self.configData.push(ddrmc1_eff);
    // }
    // if (indexFindDDRMC2 > -1)
    //     self.configData.splice(indexFindDDRMC2, 1);
    // if (ddr2indexFind > -1){
    //     self.configData.push(ddrmc2_eff);
    // }
    // if (indexFindDDRMC3 > -1)
    //     self.configData.splice(indexFindDDRMC3, 1);
    // if (ddr3indexFind > -1){
    //     self.configData.push(ddrmc3_eff);
    // }


    let request = self.$.configperf.generateRequest();
    request.completes.then(req => {
      if (req.response && req.response.status === "Fail") {
        notificationRef.setAttribute('text', 'Please connect to board and try again');
      } else if (req.response && req.response.error) {
        notificationRef.setAttribute('text', req.response.error);
      } else {
        let result = req.response.response;

        const dcIndex = _.findIndex(result, {
          "displayname": "DC"
        }); // const ddr0effIndex = _.findIndex(result,  {"displayname": "DDRMC0_Efficiency"});
        // const ddr1effIndex = _.findIndex(result,  {"displayname": "DDRMC1_Efficiency"});
        // const ddr2effIndex = _.findIndex(result,  {"displayname": "DDRMC2_Efficiency"});
        // const ddr3effIndex = _.findIndex(result,  {"displayname": "DDRMC3_Efficiency"});


        if (dcIndex > -1) result.splice(dcIndex, 1); // if (ddr0effIndex > -1)
        //     result.splice(ddr0effIndex, 1);
        // if (ddr1effIndex > -1)
        //     result.splice(ddr1effIndex, 1);
        // if (ddr2effIndex > -1)
        //     result.splice(ddr2effIndex, 1);
        // if (ddr3effIndex > -1)
        //     result.splice(ddr3effIndex, 1);

        configObj['configperf'] = result;
        if (_.findIndex(result, {
          "permission": true
        }) < 0) localStorage.setItem('configperf', []);else localStorage.setItem('configperf', JSON.stringify(result));
        window.history.pushState({}, null, '/xregv');
        window.location.reload();
        notificationRef.setAttribute('text', 'Performance is configured');
      }

      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
    }, () => {
      // if (indexFind > -1)
      //     self.configData.splice(indexFind, 1);
      // if (ddr1indexFind > -1)
      //     self.configData.splice(ddr1indexFind, 1);
      // if (ddr2indexFind > -1)
      //     self.configData.splice(ddr2indexFind, 1);
      // if (ddr3indexFind > -1)
      //     self.configData.splice(ddr3indexFind, 1);
      if (request.status == 400) redirectToLogin();
    });
  }

  _handleErrorResponse(req) {
    handleErrorResponse(req);
  }

  _updateDatabase() {
    let selectedVersion = this.shadowRoot.querySelector("#selectedVersion").selectedItem.innerText;
    const session = JSON.parse(localStorage.getItem('storedUser'));
    session.version = selectedVersion;
    localStorage.setItem('storedUser', JSON.stringify(session));
    this.parentNode.parentNode.parentNode.querySelector('#configurationmodal').close();
    window.history.pushState({}, null, '/xregv');
    window.location.reload();
  }

  ready() {
    super.ready();
    const heading = this.dataset.key;
    this.connected = false;
    this.perfConfig = false;
    this.databaseconfig = false;
    this.board = false;

    if (heading === "Connect") {
      this.connected = true;
      this.heading = "Connect to a board";
    } else if (heading === 'Board') {
      this.board = true; //this.devicedna = MyAppGlobals.appRef.devicedna;

      this.refclk = MyAppGlobals.appRef.refclk;
      this.boardname = MyAppGlobals.appRef.boardname;
      this.freadStatus = MyAppGlobals.appRef.freadstatus === "1" ? true : false;
      this.portNum = MyAppGlobals.appRef.portNum;
      this.heading = 'Board Details';
    } else if (heading === 'Performance') {
      this.perfConfig = true;
      this.heading = 'Performance Configuration';
    } else if (heading === 'Database') {
      this.databaseconfig = true;
      this.heading = 'Database Configuration';
    }

    const session = JSON.parse(localStorage.getItem('storedUser'));
    let dblist = session.versionarray;
    this.databaselist = session.versionarray;
    this.versionindex = dblist.indexOf(session.version);
    let saveObj = [];
    if (localStorage.getItem('configperf')) saveObj = JSON.parse(localStorage.getItem('configperf'));
    if (saveObj.length > 0) this.configData = saveObj;
    document.querySelector("#pageloader").style.display = "none";
  }

  _freadChanged() {
    document.querySelector("#pageloader").style.display = "block";
    let freadval = this.freadStatus === true ? "1" : "0";
    this.memaccessurl = api_url + 'setmemaccess/?enable=' + freadval;
    const session = JSON.parse(localStorage.getItem('storedUser'));
    this.$.setmemaccessxhr.headers['uid'] = session.uid;
    let request = this.$.setmemaccessxhr.generateRequest();
    request.completes.then(req => {
      if (req.response && req.response.status === "Fail") {
        notificationRef.setAttribute('text', 'Please connect to board and try again');
      } else if (req.response && req.response.error) {
        notificationRef.setAttribute('text', req.response.message);
      } else {
        if (req.response && req.response.status === "Success") {
          MyAppGlobals.appRef.freadstatus = freadval;
          localStorage.setItem('freadstatus', freadval);
        }

        notificationRef.setAttribute('text', req.response.message);
      }

      notificationRef.open();
      document.querySelector("#pageloader").style.display = "none";
    }, () => {
      if (request.status == 400) redirectToLogin();
    });
  }

}

window.customElements.define('configuration-view', Userconfiguration);