import { Location } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import { ContactEmailFormModel } from '@app/core/model/contact/contact-email-form-model';
import { ContactSupportService } from '@app/core/services/contact-support/contact-support.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { BaseComponent } from '@common/base/base.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';
import { FormService } from '@common/forms/form-service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
	selector: 'app-contact-content',
	templateUrl: './contact-content.component.html',
	styleUrls: ['./contact-content.component.scss']
})
export class ContactContentComponent extends BaseComponent implements OnInit {

	@Input() isDialog: boolean;
	@Input() form: FormGroup;
	private contactEmailFormModel: ContactEmailFormModel;
	public formGroup: FormGroup;

	constructor(
		private contactSupportService: ContactSupportService,
		private _location: Location,
		private uiNotificationService: UiNotificationService,
		private language: TranslateService,
		private formService: FormService,
		private httpClient: HttpClient,
		private matomoService: MatomoService
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('Contact Content');
		if (this.isDialog) {
			this.formGroup = this.form;
		} else {
			this.contactEmailFormModel = new ContactEmailFormModel();
			this.formGroup = this.contactEmailFormModel.buildForm();
		}
	}

	cancel() {
		this._location.back();
	}

	send() {
		this.contactSupportService.postEmail(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				complete => this.onCallbackSuccess(),
				error => this.onCallbackError(error)
			);
		this.formGroup.reset();
	}

	onCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-EMAIL-SEND'), SnackBarNotificationLevel.Success);
	}

	onCallbackError(errorResponse: any) {
		this.setErrorModel(errorResponse.error);
		this.formService.validateAllFormFields(this.formGroup);
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-EMAIL-SEND'), SnackBarNotificationLevel.Error);
	}

	public setErrorModel(validationErrorModel: ValidationErrorModel) {
		Object.keys(validationErrorModel).forEach(item => {
			(<any>this.contactEmailFormModel.validationErrorModel)[item] = (<any>validationErrorModel)[item];
		});
	}
}
