/*
* 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 { api_url, notificationRef, configObj } from '../../shared/constants.js';
import { checkKeyUp } from '../../shared/shared-script';

class XSearch extends PolymerElement {
  static get template() {
    return html`
        <style>
            :host {
              display: block;
            }
            paper-button {
              background-color: #1E88E5;
              color:white;
              height:30px;
              float:right;
              font-size:14px;
            }
            .searchFields {
                display: flex;
                justify-content: space-between;
                margin-bottom: 10px;
                flex-wrap: wrap;
            }
            h2::after {
                display: block;
                content: '';
                clear: both;
            }
            .errorText {
                text-align: center;
                vertical-align: middle;
                color: #000;
            }
            paper-input,
            paper-dropdown-menu {
                --paper-input-container-label: {
                    font-size: 20px;
                }
            }
            paper-dropdown-menu {
                --paper-dropdown-menu: {
                    width : 100px;
                }
            }
            paper-input.sizeBlk {
                --paper-input-container : {
                    width: 70px;
                }
            }
            .noteText {
                font-size: 12px;
                font-weight: normal;
                float: left;
            }
            .fieldBlk {
                width: 9em;
            }
        </style>
        <div id="xsearchmodules">
          <h2>
            <div class="searchFields" id="searchField">
                <!-- <paper-dropdown-menu always-float-label label="Module" on-iron-select="_itemSelected" class="searchValue" id="selectedModule">
                    <paper-listbox slot="dropdown-content" class="dropdown-content" selected="1">
                        <paper-item>ALL</paper-item>
                        <template is="dom-repeat" items={{moduleLists}}>
                            <paper-item>[[item]]</paper-item>
                        </template>
                    </paper-listbox>
                </paper-dropdown-menu> -->
                <paper-input type="number" value="0" hidden on-keyup="_checkKeyUp" auto-validate required id="rowvalue" class="sizeBlk" always-float-label label="Row *" min="0" max="8"></paper-input>
                <paper-input type="number" value="0" hidden on-keyup="_checkKeyUp" auto-validate required id="columnvalue" class="sizeBlk" always-float-label label="Column *" min="0" max="49"></paper-input>
                <paper-input class="fieldBlk" always-float-label placeholder="e.g. abc*, *def*, *xyz, 0xfa0" label="Module Name/Address" id="moduleName" class="searchValue"></paper-input>
                <paper-input class="fieldBlk" always-float-label placeholder="e.g. abc*, *def*, *xyz, 0xfa0" label="Register Name/Address" id="registerName" class="searchValue"></paper-input>
                <paper-input always-float-label placeholder="e.g. abc*, *def*, *xyz" label="Bit Field Name" id="bitwiseName" class="searchValue"></paper-input>
            </div>
            <!-- <span class="noteText" id="notetext"> <b> Note : </b> 'ALL' option will exclude AI Engine. </span> -->
            <paper-button raised noink on-tap="_generateSearchTable">Search</paper-button>
          </h2>
          <div id="foundDataTable"></div>
          <div id="errorMsg" class="errorText" style="display:none;">
            <span><iron-icon icon="warning"></iron-icon>No match found</span>
          </div>
          </div>
          `;
  }
  static get properties() {
    return {
      urlsearch: {
        type: String,
        value: api_url+'phrasesearch'
      },
      moduleLists: {
          type: Array,
          value: ['PS', 'PMC', 'CPM']//, 'AI Engine', 'NPI', 'DDR'
      },
      searchbody: {
          type: Object,
          value: {}
      },
      key: {
          type: String,
          value: ''
      }
    };
  }

  /* _itemSelected(e) {
    const selectedItem = e.target.selectedItem.innerText.trim();
    if (selectedItem !== "AI Engine") {
      this.$.rowvalue.setAttribute('hidden', 'hidden');
      this.$.columnvalue.setAttribute('hidden', 'hidden');
    } else {
      this.$.rowvalue.removeAttribute('hidden');
      this.$.columnvalue.removeAttribute('hidden');
    }
    if (selectedItem === 'ALL')
      this.$.notetext.removeAttribute('hidden');
    else
      this.$.notetext.setAttribute('hidden', 'hidden');
    this.$.rowvalue.value = 0;
    this.$.columnvalue.value = 0;
    this.$.moduleName.value = '';
    this.$.registerName.value = '';
    this.$.bitwiseName.value = '';
  } */

  _checkKeyUp(e) {
    checkKeyUp(e);
  }

  _generateSearchTable() {
    let data = {};
    let selectOption = "PS";//this.$.selectedModule.selectedItem.innerText.trim();
    data.hw_name = ["am012"];
    // if (selectOption === "AI Engine") {
    //   const row = this.$.rowvalue.value;
    //   const col = this.$.columnvalue.value;
    //   if (row === '' || col === '') {
    //     this.$.rowvalue.validate();
    //     this.$.columnvalue.validate();
    //     notificationRef.setAttribute('text', 'Please fill mandatory field');
    //     notificationRef.open();
    //     return;
    //   }
    //   data.row = row;
    //   data.column = col;
    //   configObj['aie_row'] = row;
    //   configObj['aie_col'] = col;
    //   selectOption = selectOption.replace(/ /g, '_');
    // }
    // if (selectOption === 'ALL')
    //   data.hw_name = this.moduleLists.filter((value) => value != 'AI Engine');
    // else
    //   data.hw_name.push(selectOption);
    this.key = selectOption.toLowerCase();
    if (this.$.moduleName.value) {
      data.instance_name = [];
      if (this.$.moduleName.value.indexOf(',') > -1) {
        const items = this.$.moduleName.value.split(',');
        data.base_address = [];
        _.map(items, (value) => {
          const item = value.trim();
          if (item) {
            if (item.length > 2 && item.indexOf('0x') > -1)
              data.base_address.push(item.toLowerCase());
            else
              data.instance_name.push(item);
          }
        });
      } else {
        const item = this.$.moduleName.value.trim();
        data.base_address = [];
        if (item.length > 2 && item.indexOf('0x') > -1)
          data.base_address.push(item.toLowerCase());
        else
          data.instance_name.push(item);
      }
    }
    if (this.$.registerName.value) {
      data.register_name = [];
      if (this.$.registerName.value.indexOf(',') > -1) {
        const items = this.$.registerName.value.split(',');
        data.register_address = [];
        _.map(items, (value) => {
          const item = value.trim();
          if (item) {
            if (item.length > 2 && item.indexOf('0x') > -1)
              data.register_address.push(item.toLowerCase());
            else
              data.register_name.push(item);
          }
        });
      } else {
        const item = this.$.registerName.value.trim();
        data.register_address = [];
        if (item.length > 2 && item.indexOf('0x') > -1)
          data.register_address.push(item.toLowerCase());
        else
          data.register_name.push(item);
      }
    }
    if (this.$.bitwiseName.value) {
      data.fields_name = [];
      if (this.$.bitwiseName.value.indexOf(',') > -1)
        data.fields_name = this.$.bitwiseName.value.split(',');
      else
        data.fields_name.push(this.$.bitwiseName.value.trim());
      data.fields_name = data.fields_name.filter(v => v != '');
    }
    this.searchbody = JSON.stringify(data);
    let flag = 0;
    _.each(Object.keys(data), (element) => {
      if (flag)
        return;
      _.each(data[element], (item) => {
        if (item.indexOf(' ') > -1) {
          flag = 1;
          return;
        }
      })
    });
    if (flag) {
      notificationRef.setAttribute('text', 'Please remove extra spaces');
      notificationRef.open();
      return;
    }
    let loadTemp = '';
    let importScript = '';
    if (this.$.bitwiseName.value) {
        loadTemp = selectOption === "AI_Engine" ? 'me-bit-fields' : 'bitfields-table';
        importScript = selectOption === "AI_Engine" ? 'me-bitfields' : 'bitfields-table';
    } else if (this.$.registerName.value) {
        loadTemp = selectOption === "AI_Engine" ? 'me-register-table' : 'register-table';
        importScript = selectOption === "AI_Engine" ? 'me-register' : 'register-table';
    } else {
        loadTemp = selectOption === "AI_Engine" ? 'me-data' : 'module-table';
        importScript = selectOption === "AI_Engine" ? 'me-module' : 'module-table';
    }
    this.$.foundDataTable.innerHTML = `<${loadTemp} data-urlsearch=${this.urlsearch} data-searchbody=${this.searchbody} key=${this.key}></${loadTemp}>`;
    selectOption === "AI_Engine" ? import(`./${importScript}.js`): import(`./../../shared/${importScript}.js`);
    document.querySelector("#pageloader").style.display = "block";
  }

  ready() {
    super.ready();
    this.addEventListener("keypress", (e) => {
      if (e.key === "Enter")
        this._generateSearchTable();
    });
  }
}
window.customElements.define('xs-search', XSearch);