import { Component, Prop, Vue } from 'vue-property-decorator';
import { notifyError } from '@utils/notify';

@Component({})
export default class BasePreview extends Vue {
  @Prop({
    default: '',
    required: true,
  })
  content: string;

  loading = false;
  dialog = false;
  isPrint = false;

  $refs!: {
    fileContainer: HTMLDivElement;
  };

  async generatePreview(): Promise<void> {
    if (!this.content) return;
    this.loading = true;
    try {
      this.showText();
    } catch (e) {
      if (e instanceof Error) notifyError(e.message);
      this.$emit('close');
    }
  }

  showText(): void {
    const container = this.$refs.fileContainer;
    const pre = document.createElement('pre');
    pre.innerText = this.content;
    pre.classList.add('PreviewDialog__Pre');
    container.classList.add('PreviewDialog__Container');
    container.appendChild(pre);
    this.loading = false;
  }

  startPrint(): void {
    this.isPrint = true;
    this.$nextTick(() => {
      window.print();
      this.isPrint = false;
    });
  }

  clickHandler(): void {
    this.dialog = true;
  }

  clearModel(): void {
    this.loading = false;
    this.dialog = false;
    if (this.$refs.fileContainer?.firstChild) {
      this.$refs.fileContainer.removeChild(this.$refs.fileContainer.firstChild);
    }
    this.$emit('close');
  }

  destroyed(): void {
    this.clearModel();
  }
}
