<template>
  <div class="row q-col-gutter-x-md full-height q-pb-xl">
    <div class="col-4">
      <div>
        <span class="text-h6">
          {{ title }}
        </span>
      </div>
      <div class="q-gutter-sm">
        <q-radio
          v-for="logType in logTypes"
          :key="logType"
          v-model="type"
          :val="logType"
          :label="$t(`services.emulation.${logType}`)"
        />
      </div>
      <div>
        <q-btn
          color="primary"
          filled
          :label="$t('services.emulation.get')"
          :loading="loading"
          @click="getLog"
        />
      </div>
    </div>
    <div class="col-8 bg-grey-1 full-height">
      <v-json-editor
        v-model="json"
        class="full-height"
        :options="{
          mode: 'code',
          mainMenuBar: false,
          onEditable: () => false,
        }"
      />
    </div>
  </div>
</template>

<script lang="ts">
// @ts-ignore
import VJsonEditor from 'v-jsoneditor';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { DefaultApi, ProcessLogs } from '@openapi/cwf';
import { notifyError } from '@/utils/notify';

enum LogType {
  Full = 'full',
  Extended = 'extended',
  Brief = 'brief',
  println = 'println',
}

const cwfApi = new DefaultApi();

@Component({
  components: {
    VJsonEditor,
  },
})
export default class extends Vue {
  @Prop() traceId!: string;
  @Prop() title: string;
  logTypes = Object.values(LogType);

  type = LogType.Full;
  loading = false;
  json = '' as ProcessLogs | string;

  mounted() {
    if (this.traceId) {
      this.getLog();
    }
  }

  @Watch('traceId')
  public async getLog() {
    const requestMethod = this.getLogMethod();
    if (!requestMethod) {
      return;
    }
    this.loading = true;
    try {
      const { data } = await requestMethod();
      this.json = data;
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    } finally {
      this.loading = false;
    }
  }

  getLogMethod() {
    switch (this.type) {
      case LogType.Full:
        return async () => cwfApi.processLogs(this.traceId);
      case LogType.Extended:
        return async () => cwfApi.processLogs2(this.traceId, true);
      case LogType.Brief:
        return async () => cwfApi.processLogs2(this.traceId, false);
      case LogType.println:
        return async () => cwfApi.processedScripts(this.traceId);
    }
  }
}
</script>
