import { Component, OnInit } from "@angular/core";
import { FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from "@angular/router";
import { EmailConfirmationService } from '@app/core/services/email-confirmation/email-confirmation.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from "rxjs/operators";

@Component({
	selector: 'app-email-confirmation-component',
	templateUrl: './email-confirmation.component.html'
})
export class EmailConfirmation extends BaseComponent implements OnInit {

	public emailFormControl = new FormControl('');
	public showForm: boolean = false;
	public mailSent: boolean = false;

	constructor(
		private emailConfirmationService: EmailConfirmationService,
		private route: ActivatedRoute,
		private router: Router,
		private language: TranslateService,
		private uiNotificationService: UiNotificationService
	) { super(); }

	ngOnInit() {
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe(params => {
				const token = params['token']
				if (token != null) {
					this.showForm = false;
					this.emailConfirmationService.emailConfirmation(token)
						.pipe(takeUntil(this._destroyed))
						.subscribe(
							result => this.onCallbackEmailConfirmationSuccess(),
							error => this.onCallbackError(error)
						)
				} else {
					this.showForm = true;
				}
			});
	}

	sendConfirmationEmail() {
		this.emailConfirmationService.sendConfirmationEmail(this.emailFormControl.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				result => this.onCallbackSuccess(),
				error => this.onCallbackError(error)
			)
	}

	onCallbackSuccess() {
		this.mailSent = true;
	}

	onCallbackEmailConfirmationSuccess() {
		this.router.navigate(['home']);
	}

	onCallbackError(error: any) {
		if (error.status === 302) {
			this.uiNotificationService.snackBarNotification(this.language.instant('EMAIL-CONFIRMATION.EMAIL-FOUND'), SnackBarNotificationLevel.Warning);
			this.router.navigate(['home']);
		} else {
		this.uiNotificationService.snackBarNotification(this.language.instant('EMAIL-CONFIRMATION.EXPIRED-EMAIL'), SnackBarNotificationLevel.Error);
		this.router.navigate(['login']);
		}
	}
}
