import { Component, OnInit } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { marker } from '@biesbjerg/ngx-translate-extract-marker';
import { AppStorage } from 'src/app/shared/app-storage';
import { AuthService } from 'src/app/shared/server-services/auth.service';
import { DialogService } from 'src/app/shared/services/dialog.service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';
import { TitleService } from 'src/app/shared/services/title.service';
import { styleChangedObserver } from 'src/app/shared/shared-observers';

@Component({
  selector: 'app-register-confirm',
  templateUrl: './register-confirm.component.html',
  styleUrls: ['./register-confirm.component.scss'],
})
export class RegisterConfirmComponent implements OnInit {
  private token;
  private salt;
  public isPending: boolean = false;
  public isRegisterSuccess: boolean = false;
  private trial = 0;
  public isDarkTheme: boolean = true;

  registerConfirmForm = new UntypedFormGroup({
    email: new UntypedFormControl('', [Validators.required, Validators.email]),
    password: new UntypedFormControl('', [Validators.required]),
  });

  constructor(
    private routerHandler: RouterHandler,
    private authService: AuthService,
    private dialogService: DialogService,
    private titleService: TitleService
  ) {
    this.titleService.setTabTitle(marker('Confirm registration'));
    this.isDarkTheme = AppStorage.getItem('style_mode') == 'dark';
    styleChangedObserver.subscribe((style) => {
      this.isDarkTheme = style == 'dark';
    });
  }

  public startRegisterConfirm() {
    var email = this.registerConfirmForm.get('email').value;
    var password = this.registerConfirmForm.get('password').value;

    this.isPending = true;
    this.authService
      .registerConfirm(this.token, email, password)
      .then(() => {
        this.isPending = false;
        this.isRegisterSuccess = true;
        // confimation success force the user to login
        this.dialogService.openAlertDialog(
          marker('Successful confirmation'),
          marker('Your account is confirmed. Please try to login')
        );
        this.routerHandler.navigate(['/login']);
      })
      .catch((err) => {
        console.error('wrong input data', err);

        this.trial++;
        this.isPending = false;

        if (err.error == 'Email is already taken by deleted account!') {
          this.dialogService.openAlertDialog(
            marker('Email taken'),
            marker('Email is already taken by a deleted account!')
          );
        } else if (this.trial == 1) {
          this.dialogService.openAlertDialog(
            marker('Confirmation Error'),
            marker('Something went wrong, please try again.')
          );
        } else if (this.trial == 2) {
          this.dialogService.openAlertDialog(
            marker('Confirmation Error'),
            marker('Something went wrong. Check your email and password again.')
          );
        } else if (this.trial == 3) {
          this.dialogService.openAlertDialog(
            marker('Confirmation Error'),
            marker('Something went wrong. Try to reopen your link from your email.')
          );
        } else if (this.trial == 4) {
          this.dialogService.openAlertDialog(
            marker('Confirmation Error'),
            marker(
              'Something went wrong. If you can not confirm your account, you can try to register again.'
            )
          );
        } else if (this.trial > 4) {
          this.dialogService.openAlertDialog(
            marker('Confirmation Error'),
            marker(
              'Something went wrong. If you can not confirm you account, you can contact our support.'
            )
          );
        }
        this.registerConfirmForm.get('password').setValue('');
      });
  }

  ngOnInit(): void {
    let fragment = this.routerHandler.getRoute().fragment['register-confirm'];
    if (fragment) {
      this.token = fragment;
      console.log('ok, start to confirm register', this.token);
    }
  }
}
