import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ProfileService } from 'src/app/Services/profile.service';
import { ConfirmationDialogComponent } from './confirmation-dialog/confirmation-dialog.component';
import { HelpDialogComponent } from './help-dialog/help-dialog.component';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss'],
})
export class ProfileComponent implements OnInit {
  userNameFormControl = new FormControl('', [Validators.required]);
  passwordFormControl = new FormControl('', [
    Validators.required,
    Validators.minLength(6),
  ]);
  passwordRepeatFormControl = new FormControl('', [
    Validators.required,
    Validators.minLength(6),
  ]);
  telegramIdFormControl = new FormControl('', [
    Validators.required,
    Validators.minLength(6),
  ]);

  userId = '';

  form: any = {
    username: null,
    email: 'example@web.com',
    password: null,
    passwordRepeat: null,
  };

  checkPasswordFailed = false;

  constructor(
    private profileService: ProfileService,
    public dialog: MatDialog
  ) {}

  ngOnInit(): void {
    this.profileService.getUserData().subscribe((result) => {
      console.log(result);
      result = JSON.parse(result);
      this.form.username = result.data.username;
      this.form.password = result.data.password;
      this.form.email = result.data.email;
      this.userId = result.data.telegram_user_id;
    });
  }

  /**
   * Determines whether submit on
   */
  onSubmit(): void {
    if (this.userId != '') {
      console.log(this.userId);
      this.profileService
        .addTelegramId('' + this.userId)
        .subscribe((result) => {
          console.log(result);
        });
    }
  }

  /**
   * Updates user
   */
  updateUser() {
    if (this.form.password === this.form.passwordRepeat) {
      this.checkPasswordFailed = false;
      const { username, email, password } = this.form;
      this.profileService
        .updateProfile(this.form.username, this.form.password)
        .subscribe((result) => {
          console.log(result);
        });
    } else {
      this.checkPasswordFailed = true;
      console.log("Passwords don't match");
    }
  }

  /**
   * Opens dialog
   * @param action
   */
  openDialog(action: string) {
    const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
      width: '50vw',
      height: '25vh',
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result === true) {
        if (action === 'addTelegram') {
          this.onSubmit();
        } else if (action === 'updateUser') {
          this.updateUser();
        }
      }
    });
  }

  /**
   * Opens help
   */
  openHelp() {
    const dialogRef = this.dialog.open(HelpDialogComponent, {
      width: '50vw',
      height: '20vh',
    });
  }
}
