/*
* 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 '@polymer/paper-input/paper-input.js';
import { api_url, notificationRef } from '../../shared/constants.js';
import '@polymer/paper-dialog/paper-dialog.js';
import './xsdb_help.js';
import '@polymer/iron-dropdown/iron-dropdown.js';
import '@polymer/iron-icons/iron-icons.js';
import '@polymer/iron-iconset-svg/iron-iconset-svg.js';
import '@polymer/paper-button/paper-button.js';
import '@polymer/paper-icon-button/paper-icon-button.js';
import '@polymer/iron-ajax/iron-ajax.js';
import '@vaadin/vaadin-upload/vaadin-upload.js';
import { GetFormattedDate, redirectToLogin, handleErrorResponse } from '../../shared/shared-script.js';
class commandInterface extends PolymerElement {
  static get template() {
    return html`
      <style>
        :host {
          display: block;
        }
        #commandInterfaceWidget {
          font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
          border: 1px solid #4285f4;
          border-radius:3px;
          width: 100%;
          margin-top:10px;
          height:440px;
        }
        #resultPane{
          max-height:390px;
          overflow-y:auto;
        }
        #commandInputSlot{
          font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
          width: 100%;
          margin:10px 0px;
          height:50px; 
        }
        #tools{
          padding:5px;
          background-color:#4285f4;
          color:#fff;
          height:40px;
        }
        #commandInputBox{
            width: calc(100% - 21.49em);
            padding: 4px 8px;
            height:28px;
        }
        button {
            width: 84px;
            height: 40px;
            /* override pointer-events: none set by app-toolbar */
            pointer-events: auto;
            cursor:pointer; 
            background-color:#4285f4;
            color:#fff;
            border-radius:3px;
            border:none;
        }
        .headTerm {
            display: inline-block;
            margin-top: .5em;
        }
        #helpmodal {
          width:80%;
          left:260px;
          position:fixed;
          top:80px;
        }
        #helpmodal .helpBoard {
          max-height: 400px;
          overflow-y: auto;
          padding: 8px;
        }
      </style>
      <div id="commandInterfaceWidget">
        <div id="tools">
            <span class="headTerm">Debugger Terminal</span>
            <!-- <a target="_blank" href="[[downloadurl]]"><paper-icon-button icon="icons:file-download" style="float:right" title="Download Log File"></paper-icon-button></a> -->
            <paper-icon-button icon="icons:clear" style="float:right" on-tap="_clearResult" title="Clear Console"></paper-icon-button>
            <!-- <paper-icon-button icon="icons:help" style="float:right" on-tap="_loadxsdbhelp" title="XSDB Help"></paper-icon-button> -->
        </div>
        <div id="resultPane">
        </div>
      </div>
      <div id="commandInputSlot">
        <input id="commandInputBox" type="text" on-keyup="_userPreference"></input>
        <button id="sendCommand" on-tap="_sendCommand">Send</button>
        <!-- <button id="enablemdmbtn" on-tap="_enablemdm">Enable</button> -->
        <button on-tap="_clearInput">Clear</button>
      </div>
      <div id="fileUpload">
        <vaadin-upload accept=".tcl,.xregv" headers={{headers}} target=[[fileuploadurl]] max-file-size="1000000">
          <iron-icon slot="drop-label-icon" icon="description"></iron-icon>
          <span slot="drop-label">Please upload .tcl, .xregv files</span>
        </vaadin-upload>
      </div>
      <paper-dialog id="helpmodal">
          <div class="helpBoard">
            <xsdb-help-table></xsdb-help-table>
          </div>
      </paper-dialog>
      <iron-ajax id="sendcommand" method="post" url="[[url]]" body={{livecommand}} handle-as="json" content-type="application/json" last-response="{{handleResponse}}" on-error="_handleErrorResponse"></iron-ajax>
      <iron-ajax id="enablemdmcall" method="get" url="[[enablemdmurl]]" handle-as="json" content-type="application/json" on-error="_handleErrorResponse"></iron-ajax>
      `;
  }
  static get properties() {
    return {
      url: {
        type: String,
        value: `${api_url}runcommand/`
      },
      downloadurl: {
        type: String,
        value: ''
      },
      fileuploadurl: {
        type: String,
        value: `${api_url}runcommandfile/`
      },
      livecommand: {
        type: Object,
        value: { "command": "" },
      },
      userPrefCmd: {
        type: Array,
        value: []
      },
      userPrefLen: {
        type: Number,
        value: 0
      },
      headers: {
        type: Object,
        value: { 'uid': '' }
      },
      enablemdmurl: {
        type: String,
        value: `${api_url}enablemdm/`
      }
    };
  }

  _handleErrorResponse(req) {
    handleErrorResponse(req);
  }

  _sendCommand(e) {
    let commandVal = e.currentTarget.parentNode.querySelector("input").value;
    if (commandVal !== "") {
      this.livecommand.command = commandVal;
      document.querySelector("#pageloader").style.display = "block";
      let self = this;
      const session = JSON.parse(localStorage.getItem('storedUser'));
      self.$.sendcommand.headers['uid'] = session.uid;
      let request = self.$.sendcommand.generateRequest();
      request.completes.then((req) => {
        let result = req.response;
        if (result.status === 'Fail') {
          notificationRef.setAttribute('text', 'Please Connect to board and try again');
          notificationRef.open();
          document.querySelector("#pageloader").style.display = "none";
          return;
        }
        if (self.userPrefCmd[self.userPrefCmd.length - 1] !== commandVal)
          self.userPrefCmd.push(commandVal);
        self.$.commandInputBox.value = "";
        let cliresp = `<div>>> ${result.command} </div>&nbsp&nbsp&nbsp&nbsp`;
        cliresp = self._insertformatteddata(cliresp, result);
        self.$.resultPane.innerHTML += cliresp;
        self.$.resultPane.scrollTop = self.$.resultPane.scrollHeight;
        self.userPrefLen = self.userPrefCmd.length;
        document.querySelector("#pageloader").style.display = "none";
      }, () => {
        if (request.status == 400)
          redirectToLogin();
      });
    }
  }

  /* _enablemdm() {
    let self = this;
    document.querySelector("#pageloader").style.display = "block";
    const session = JSON.parse(localStorage.getItem('storedUser'));
    self.$.enablemdmcall.headers['uid'] = session.uid;
    let request = self.$.enablemdmcall.generateRequest();
    request.completes.then((req) => {
      let result = req.response;
      if (result.status === 'Fail') {
        notificationRef.setAttribute('text', 'Please Connect to board and try again');
        notificationRef.open();
        document.querySelector("#pageloader").style.display = "none";
        return;
      }
      let cliresp = "<div>>> ";
      cliresp = self._insertformatteddata(cliresp, result);
      self.$.resultPane.innerHTML += cliresp;
      self.$.resultPane.scrollTop = self.$.resultPane.scrollHeight;
      document.querySelector("#pageloader").style.display = "none";
    }, () => {
      if (request.status == 400)
        redirectToLogin();
    });
  } */

  _insertformatteddata(cliresp, result) {
    for (let i = 0; i < result.response.length; i++) {
      if (result.response[i] !== "")
        cliresp += result.response[i] + "<br>&nbsp&nbsp&nbsp&nbsp";
    }
    cliresp += "</div>";
    return cliresp;
  }

  _userPreference(e) {
    if (e.keyCode === 38) {
      if (this.userPrefLen - 1 >= 0) {
        this.$.commandInputBox.value = this.userPrefCmd[--this.userPrefLen];
      }
    } else if (e.keyCode === 40) {
      if (this.userPrefCmd.length > this.userPrefLen + 1) {
        this.$.commandInputBox.value = this.userPrefCmd[++this.userPrefLen]
      } else {
        this.$.commandInputBox.value = '';
        this.userPrefLen = this.userPrefCmd.length;
      }
    }
  }

  _clearInput() {
    this.$.commandInputBox.value = "";
  }

  _executeCommand(e) {
    if (e.key === "Enter") {
      this.$.sendCommand.click();
    }
  }

  _clearResult() {
    this.$.resultPane.innerHTML = "";
  }

  _loadxsdbhelp() {
    this.$.helpmodal.open();
  }

  ready() {
    super.ready();
    document.querySelector("#pageloader").style.display = "none";
    const session = JSON.parse(localStorage.getItem('storedUser'));
    const uid = session.uid;
    this.downloadurl = `${api_url}logfiles/${uid}/Debugger.txt`;
    this.$.commandInputBox.addEventListener('keypress', e => this._executeCommand(e));
    this.headers.uid = session.uid;
  }
}
window.customElements.define('command-interface', commandInterface);