<i18n>
{
  "en": {
    "ResourcesUploadForm": {
      "title": "Resource description",
      "description": "Select OpenAPI file",
      "server": "Select a server",
      "serviceDescription": "Service description",
      "more": "Show more",
      "send": "Send"
    }
  },
  "ru": {
    "ResourcesUploadForm": {
      "title": "Описание ресурса",
      "description": "Описание в формате OpenAPI",
      "server": "Выберите сервер",
      "serviceDescription": "Описание сервиса",
      "more": "Подробнее",
      "send": "Отправить"
    }
  }
}
</i18n>
<template>
  <div>
    <q-form class="q-gutter-y-md" @submit="submit">
      <div class="text-h6">{{ $t('ResourcesUploadForm.title') }}</div>
      <div class="row q-gutter-y-md">
        <div class="col-12">
          <q-file
            v-model="swaggerFile"
            color="primary"
            filled
            :label="$t('ResourcesUploadForm.description') + '*'"
            accept=".yaml, .yml"
            @input="inputHandler"
          >
            <template #append>
              <q-icon name="attach_file" />
            </template>
          </q-file>
        </div>
      </div>
      <div v-if="servers.length" class="row q-gutter-y-md">
        <div class="col-12">
          <q-select
            v-model="selectedServer"
            filled
            use-input
            use-chips
            single
            :options="serverOptions"
            :label="$t('ResourcesUploadForm.server') + '*'"
            @new-value="addServer"
          />
        </div>
      </div>
      <div v-if="servers.length" class="row q-gutter-y-md">
        <div class="col-12">
          <q-input
            v-model="description"
            filled
            :label="$t('ResourcesUploadForm.serviceDescription')"
          />
        </div>
      </div>
      <div v-show="expand" id="swagger-ui"></div>
      <div class="row q-gutter-y-md">
        <q-card v-if="infoCard" bordered class="bg-white my-card full-width">
          <q-card-section>
            <div class="text-h6">{{ infoCard.title }}</div>
            <div class="text-subtitle2">{{ infoCard.version }}</div>
          </q-card-section>

          <q-separator />

          <q-card-section>
            {{ infoCard.description }}
          </q-card-section>

          <q-separator />

          <q-card-actions>
            <q-btn
              color="primary"
              :label="$t('ResourcesUploadForm.more')"
              @click="showMore"
            />
            <q-btn
              color="primary"
              :disable="!swaggerFile"
              :label="$t('ResourcesUploadForm.send')"
              type="submit"
            />
          </q-card-actions>
        </q-card>
      </div>
    </q-form>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
// @ts-ignore
import SwaggerUI from 'swagger-ui';
import { safeLoad, safeDump } from 'js-yaml';
import { WorkflowServiceApi } from '@openapi/wf';

const wfApi = new WorkflowServiceApi();

export default {
  props: ['input-data'],
  data() {
    return {
      swaggerFile: null,
      swaggerFileParsed: null,
      servers: [],
      serverOptions: [],
      infoCard: null,
      expand: false,
      selectedServer: '',
      description: '',
    };
  },
  computed: {
    outputData() {
      return {
        contentType: 'application/yaml',
        swaggerFileParsed: this.swaggerFileParsed,
      };
    },
  },
  watch: {
    swaggerFileParsed: {
      handler: function () {
        const ui = SwaggerUI({
          spec: this.swaggerFileParsed,
          dom_id: '#swagger-ui',
          deepLinking: true,
        });
      },
    },
  },
  methods: {
    addServer(val, done) {
      if (val.length > 0) {
        this.serverOptions.push(val);
        done(val, 'toggle');
        this.selectedServer = val;
      }
    },
    showMore() {
      this.expand = !this.expand;
    },
    inputHandler(val) {
      const fileReader = new FileReader();
      fileReader.readAsText(val);
      fileReader.onload = () => {
        this.swaggerFileParsed = safeLoad(fileReader.result);
        this.infoCard = this.swaggerFileParsed.info;
        this.servers = this.swaggerFileParsed.servers;
        for (let i = 0; i < this.servers.length; i++) {
          this.serverOptions.push(this.servers[i].url);
        }
        this.selectedServer = this.serverOptions[0];
        this.swaggerFileParsed.servers = this.selectedServer;
      };
    },
    submit(e) {
      this.swaggerFileParsed.servers = [];
      this.swaggerFileParsed.servers.push({
        url: this.selectedServer,
        description: this.description,
        variables: {},
      });
      const apiString = safeDump(this.swaggerFileParsed);
      const apiFile = new File([apiString], `${this.infoCard.title}.yaml`);
      e.preventDefault();
      wfApi.submitFormWithFiles(
        this.inputData.userTaskId,
        undefined,
        undefined,
        apiFile,
        JSON.stringify(this.outputData)
      );
    },
  },
};
</script>
