import { Component, OnInit } from "@angular/core";
import { MatDialogRef } from "@angular/material/dialog";
import { marker } from "@biesbjerg/ngx-translate-extract-marker";
import { AuthService } from "../../server-services/auth.service";
import { CordovaService } from "../../services/cordova.service";
import { DialogService } from "../../services/dialog.service";
import { NanoDialogBase } from "../nano-base-dialog";

@Component({
  selector: "app-download-recovery-code-dialog",
  templateUrl: "./download-recovery-code-dialog.component.html",
  styleUrls: ["./download-recovery-code-dialog.component.scss"],
})
export class DownloadRecoveryCodeDialogComponent
  extends NanoDialogBase<DownloadRecoveryCodeDialogComponent>
  implements OnInit
{
  constructor(
    public dialogRef: MatDialogRef<DownloadRecoveryCodeDialogComponent>,
    private authService: AuthService,
    private cordovaService: CordovaService,
    private dialogService: DialogService
  ) {
    super(dialogRef);
  }

  ngOnInit(): void {}

  downloadKey(): void {
    let name = "CBNANO-SECRET-RECOVERY-KEY.TXT";
    if (this.cordovaService.isOnApp()) {
      this.cordovaService
        .getFileWriter(name)
        .then((writer) => {
          return writer
            .write(this.authService.createRecoveryKeyFile())
            .then(() => {
              writer.close();
              this.dialogService.showSnackbar(
                marker("Downloaded:") + ": " + name
              );
            });
        })
        .catch((e) => {
          console.error("Could not create the file", e);
          this.dialogService.openAlertDialog(
            marker("Download error"),
            marker("Could not create the file")
          );
        });
    } else {
      var a;
      a = document.createElement("a");
      a.href = URL.createObjectURL(this.authService.createRecoveryKeyFile());
      a.download = name;
      document.body.appendChild(a);
      a.style = "display: none";
      a.click();
      a.remove();

      this.dialogService.showSnackbar(marker("Downloaded") + ": " + name);
    }
  }

  remindLater(): void {
    this.remindAfterMonths(1);
    this.close();
  }

  remindAfterMonths(months: number): void {
    var currentDate = new Date();
    var reminderDate = new Date(
      currentDate.setMonth(currentDate.getMonth() + months)
    );
    localStorage.setItem(
      "recoveryKeyDownloadReminderDate",
      reminderDate.toString()
    );
  }

  close(): void {
    this.remindAfterMonths(6);
    this.dialogRef.close();
  }
}
