<template>
  <div class='components-container'>
    <json-tree-table :data='json' :options='tdvOption' rootObjectKey='root' class="json-tree-table" ref="jsonTreeTable">
      <template v-slot:title>
        <a href="https://www.treedoc.org" target="_blank"><b class="tdv-title">Treedoc Extension</b></a>
        <a href='https://github.com/treedoc/TreedocViewer' target="_blank"><img alt="GitHub stars" src="https://img.shields.io/github/stars/treedoc/treedocviewer"></a>
      </template>
      <span id='icons'>
        <b-button-group class="ml-1 tdv-toolbar" v-if="urlParam.embeddedId">
          <b-btn :size="'sm'" @click='showSource' class='tdv' v-b-tooltip.hover title="Show orignal source code">Show Source</b-btn>
        </b-button-group>
      </span>
    </json-tree-table>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { YAMLParserPlugin, XMLParserPlugin, CSVParserPlugin, JSONParserPlugin, JSONParserType, JsonTreeTable, TDVOption} from 'treedoc-viewer';
import UrlParam from './UrlParam';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import 'font-awesome/css/font-awesome.css';

@Component
export default class App extends Vue {
  json = '[Loading...]';
  urlParam = new UrlParam();
  tdvOption: TDVOption = new TDVOption().setParsers([
      new JSONParserPlugin('Map.toString', JSONParserType.JAVA_MAP_TO_STRING),
      new XMLParserPlugin('XML compact', 'text/xml', true),
      new XMLParserPlugin(),
      new XMLParserPlugin('html', 'text/html'),
      new CSVParserPlugin(),
      new CSVParserPlugin('TSV', '\t'),
      new YAMLParserPlugin(),
    ]);

  private get jsonTreeTable() {
    return this.$refs.jsonTreeTable as JsonTreeTable;
  }

  mounted() {
    const url = new URL(window.location.href);
    if (this.urlParam.dataUrl)
      this.jsonTreeTable.openUrl(this.urlParam.dataUrl);

    if (window.opener) {
      console.log('window.opener.postMessage');
      window.opener.postMessage({ type: 'tdv-ready'}, '*');
    }

    window.parent.postMessage({ type: 'tdv-ready'}, '*');

    window.addEventListener('message', evt => {
      console.log(evt.data.type);
      if (evt.data.type !== 'tdv-setData')
        return;
      this.json = evt.data.data;
    }, false);
  }

  showSource() {
    window.parent.postMessage({ type: 'tdv-show-source'}, '*');
  }
}
</script>
<style scoped>
.components-container {
  display: flex;
  position: absolute;
  flex-direction: column;
  margin-left: 2px;
  width: 99%;
  /* background-color: #ff0; */
  height: 98%;
  /* overflow: auto; */
  /* min-height:100%;
  min-width:100%; */
}
#icons {
  float: right;
}
</style>
