import { Component, OnInit } from '@angular/core';
import { PasswordGeneratorService } from './password-generator.service';

@Component({
  selector: 'app-password-generator',
  templateUrl: './password-generator.component.html',
  styleUrls: ['./password-generator.component.scss']
})
export class PasswordGeneratorComponent implements OnInit {

  passwordLength: number = 12;
  includeUppercase: boolean = true;
  includeLowercase: boolean = true;
  includeNumbers: boolean = true;
  includeSymbols: boolean = true;
  excludeCharacters: string = '';
  generatedPassword: string = '';
  errorMessage: string = '';

  constructor(private passwordGeneratorService: PasswordGeneratorService) { }

  ngOnInit(): void {
  }

  generatePassword(): void {
    // Client-side validation
    if (this.passwordLength < 8 || this.passwordLength > 128) {
      this.errorMessage = 'Password length must be between 8 and 128 characters.';
      this.generatedPassword = '';
      return;
    }

    if (!this.includeUppercase && !this.includeLowercase && !this.includeNumbers && !this.includeSymbols) {
      this.errorMessage = 'At least one character type (uppercase, lowercase, numbers, symbols) must be selected.';
      this.generatedPassword = '';
      return;
    }

    this.errorMessage = '';
    this.generatedPassword = ''; // Clear previous password

    const request = {
      length: this.passwordLength,
      includeUppercase: this.includeUppercase,
      includeLowercase: this.includeLowercase,
      includeNumbers: this.includeNumbers,
      includeSymbols: this.includeSymbols,
      excludeCharacters: this.excludeCharacters
    };

    this.passwordGeneratorService.generatePassword(request).subscribe({
      next: (response) => {
        if (response.success) {
          this.generatedPassword = response.generatedPassword;
          this.errorMessage = '';
        } else {
          this.errorMessage = response.message || 'Failed to generate password.';
          this.generatedPassword = '';
        }
      },
      error: (err) => {
        this.errorMessage = err.message || 'An error occurred while generating password.';
        this.generatedPassword = '';
      }
    });
  }

  copyToClipboard(): void {
    if (this.generatedPassword) {
      navigator.clipboard.writeText(this.generatedPassword).then(() => {
        alert('Password copied to clipboard!');
      }).catch(err => {
        console.error('Could not copy text: ', err);
      });
    }
  }

}
