import { Component, Inject } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { NanoDialogBaseComponent } from '../nano-base-dialog';

export interface RenameExistingFileDialogData {
  name: string;
}

@Component({
  selector: 'app-rename-existing-file-dialog',
  templateUrl: './rename-existing-file-dialog.component.html',
  styleUrls: ['./rename-existing-file-dialog.component.scss'],
})
export class RenameExistingFileDialogComponent extends NanoDialogBaseComponent<RenameExistingFileDialogComponent> {
  public fileNameControl = new FormControl<string>('', [Validators.required]);
  public overwriteControl = new FormControl<boolean>(false);
  public extension: string = '';

  private originalName: string = '';

  constructor(
    public dialogRef: MatDialogRef<RenameExistingFileDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: RenameExistingFileDialogData
  ) {
    super(dialogRef);
    const lastPeriod = data.name.lastIndexOf('.');
    if (lastPeriod > 0) {
      this.fileNameControl.setValue(data.name.substring(0, lastPeriod));
      this.extension = data.name.substring(lastPeriod, this.data.name.length);
    } else {
      this.fileNameControl.setValue(data.name);
    }
    this.originalName = this.fileNameControl.value;
  }

  public close(): void {
    const newName = this.fileNameControl.value + this.extension;
    this.dialogRef.close(newName);
  }

  get canAccept(): boolean {
    return (
      (this.overwriteControl.value || this.fileNameControl.value != this.originalName) &&
      this.fileNameControl.valid
    );
  }
}
