import { AfterViewInit, Component, Input, OnInit } from "@angular/core";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { DriveFile } from "src/app/components/resource-page/drive-window/drive-layout/drive-file";
import { NanoService } from "src/app/shared/nano/nano.service";
import { RoomRecord } from "src/app/shared/server-services/query-records/room-records";
import { RoomService } from "src/app/shared/server-services/room.service";
import { ServerError } from "src/app/shared/server-services/server-errors";
import { DialogService } from "src/app/shared/services/dialog.service";
import {
  DownloadManagerService,
  FileManagerType,
} from "src/app/shared/services/download-manager-service";
import { RouterHandler } from "src/app/shared/services/router-handler.service";

export type AttachedFileUrl = {
  file: string;
  path: string;
  roomId: string;
};

@Component({
  selector: "app-markdown-file-preview",
  templateUrl: "./markdown-file-preview.component.html",
  styleUrls: ["./markdown-file-preview.component.scss"],
})
export class MarkdownFilePreviewComponent implements OnInit {
  @Input("fileUrl") fileUrl: AttachedFileUrl;
  public file: DriveFile;
  public roomData: RoomRecord;
  public isLoaded: boolean = false; // load the file info from nano
  public isFileValid: boolean;
  public fileCheckError: boolean = false;
  private isDownloadStarted: boolean = false;
  public downloadProgress: number = 0;

  constructor(
    private roomService: RoomService,
    private nanoService: NanoService,
    private routerHandler: RouterHandler,
    private downloadManagerService: DownloadManagerService,
    private dialogService: DialogService
  ) {}

  ngOnInit(): void {
    console.log("fileUrl", this.fileUrl);

    this.file = new DriveFile({
      name: this.fileUrl.file,
      size: 0,
      mtime: 0,
    });

    this.roomService.getData(this.fileUrl.roomId).then((roomData) => {
      this.roomData = roomData;
    });

    this.nanoService.peekFile(
      this.fileUrl.roomId,
      (this.fileUrl.path ? this.fileUrl.path + "/" : "") + this.fileUrl.file,
      (file) => {
        this.file = new DriveFile(file);
        this.isLoaded = true;
        this.isFileValid = true;
      },
      (err) => {
        if (
          err.error == ServerError.NANO_REQUEST_ERROR_HANDLER_TARGET_NOT_FOUND
        ) {
          this.isLoaded = true;
          this.isFileValid = false;
        } else {
          this.fileCheckError = true;
          this.isLoaded = true;
        }
        console.error("err", err);
      }
    );
  }

  public openPath() {
    let fragment = this.routerHandler.getRoute().fragment;
    if (this.fileUrl.path) {
      fragment["path"] = this.fileUrl.path;
    }
    fragment["file"] = this.fileUrl.file;

    this.routerHandler.navigate(["/room/", this.fileUrl.roomId, "drive"], {
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
  }

  public download() {
    if (!this.isDownloadStarted) {
      this.isDownloadStarted = true;
      this.downloadManagerService
        .download(
          this.fileUrl.roomId,
          (this.fileUrl.path ? this.fileUrl.path + "/" : "") +
            this.fileUrl.file,
          this.file,
          (curr, max, speed, timeNeeded, refForFile: FileManagerType) => {
            if (max > 0) {
              this.downloadProgress = (curr / max) * 100;
            }
          }
        )
        .then(() => {})
        .catch(() => {
          this.dialogService.openAlertDialog(
            marker("Error"),
            marker("Error happened during the file download")
          );
        })
        .finally(() => {
          this.isDownloadStarted = false;
        });
    } else {
      this.dialogService.showSnackbar(marker("Download already started!"));
    }
  }
}
