import { Component } 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 { BlobService } from '../../services/blob.service';
import { CordovaService } from '../../services/cordova.service';
import { DialogService } from '../../services/dialog.service';
import { SnackBarService } from '../../services/snackbar.service';
import { NanoDialogBaseComponent } from '../nano-base-dialog';
import { AppStorage } from 'src/app/shared/app-storage';

@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 NanoDialogBaseComponent<DownloadRecoveryCodeDialogComponent> {
  constructor(
    public dialogRef: MatDialogRef<DownloadRecoveryCodeDialogComponent>,
    private authService: AuthService,
    private cordovaService: CordovaService,
    private dialogService: DialogService,
    private blobService: BlobService,
    private snackbarService: SnackBarService
  ) {
    super(dialogRef);
  }

  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.snackbarService.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 = this.blobService.createObjectURL(this.authService.createRecoveryKeyFile());
      a.download = name;
      document.body.appendChild(a);
      a.style = 'display: none';
      a.click();
      a.remove();

      this.snackbarService.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));
    AppStorage.setItem('recoveryKeyDownloadReminderDate', reminderDate.toString());
  }

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