import { Component, Prop, PropSync, Watch, Vue } from 'vue-property-decorator';
import { convertDateFromBackendFormat } from '@utils/format-date';
import QColumn from '@/types/QColumn';
import { WorkflowServiceApi, WFSchema } from '@openapi/wf';

const wfApi = new WorkflowServiceApi();

@Component({})
export default class BaseBpmnCloudLoader extends Vue {
  @PropSync('show') showing: boolean;
  @Prop({ default: 'file' }) valueMode: keyof typeof ValueModes;

  @Watch('showing')
  showingHandler(val: boolean) {
    if (val && !this.schemas.length) {
      this.loading = true;
      wfApi
        .getCodes()
        .then(({ data }) => {
          this.schemas = data.schemas || [];
        })
        .finally(() => {
          this.loading = false;
        });
    } else if (!val) {
      this.clear();
    }
  }

  public columns: QColumn[] = [
    {
      align: 'left',
      field: 'key',
      label: 'processes.bpmnEditor.cloud.key',
      name: 'key',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'name',
      label: 'processes.bpmnEditor.cloud.name',
      name: 'name',
      sortable: true,
    },
    {
      field: 'version',
      label: 'processes.bpmnEditor.cloud.version',
      name: 'version',
      sortable: true,
    },
    {
      align: 'left',
      field: 'date',
      format: (val: string) => convertDateFromBackendFormat(val),
      label: 'processes.bpmnEditor.cloud.date',
      name: 'date',
      sortable: true,
    },
  ];

  public filter = '';
  public initialPagination = {
    rowsPerPage: 10,
  };

  public loading = false;
  public schemas: WFSchema[] = [];
  public selected: WFSchema[] = [];

  protected clear() {
    this.selected = [];
    this.filter = '';
  }

  protected selectHandler(): void {
    this.showing = false;
    this.loading = true;
    const code: string = this.selected[0]?.key || '';

    wfApi
      .getSchema(code)
      .then(({ data: resp }) => {
        // todo OPENAPI response void
        // @ts-ignore
        const xml: string = (resp || '').toString();
        this.emitValueByMode(xml, code);
      })
      .finally(() => {
        this.loading = false;
      });
  }

  protected emitValueByMode(xml: string, code: string) {
    const blob: Blob = new Blob([xml], {
      type: 'text/xml',
    });
    const file: File = new File([blob], `${code.trim()}.bpmn`);
    switch (this.valueMode) {
      case ValueModes.file:
        this.$emit('getBpmn', {
          code,
          value: file,
        });
        break;
      case ValueModes.string:
        this.$emit('getBpmn', {
          code,
          value: xml,
        });
        break;
    }
  }
}

enum ValueModes {
  string = 'string',
  file = 'file',
}
