
import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { DmpModel } from '@app/core/model/dmp/dmp';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { FunderFormModel } from '@app/ui/dmp/editor/grant-tab/funder-form-model';
import { GrantTabModel } from '@app/ui/dmp/editor/grant-tab/grant-tab-model';
import { ProjectFormModel } from '@app/ui/dmp/editor/grant-tab/project-form-model';
import { DmpWizardEditorModel } from '@app/ui/dmp/wizard/dmp-wizard-editor.model';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
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 { Observable, of as observableOf } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-dmp-wizard-component',
	templateUrl: 'dmp-wizard.component.html',
	styleUrls: ['./dmp-wizard.component.scss'],
})
export class DmpWizardComponent extends BaseComponent implements OnInit, IBreadCrumbComponent {

	breadCrumbs: Observable<BreadcrumbItem[]>;
	itemId: string;
	dmp: DmpWizardEditorModel;
	formGroup: FormGroup;
	isClone: boolean;
	saving = false;

	constructor(
		private dmpService: DmpService,
		private language: TranslateService,
		private snackBar: MatSnackBar,
		private route: ActivatedRoute,
		private router: Router,
		private uiNotificationService: UiNotificationService
	) { super(); }

	ngOnInit(): void {

		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe((params: Params) => {
				this.itemId = params['id'];
				this.dmpService.getSingle(this.itemId).pipe(map(data => data as DmpModel))
					.pipe(takeUntil(this._destroyed))
					.subscribe(data => {
						this.dmp = new DmpWizardEditorModel();
						this.dmp.grant = new GrantTabModel();
						this.dmp.project = new ProjectFormModel();
						this.dmp.funder = new FunderFormModel();
						this.dmp.fromModel(data);
						this.formGroup = this.dmp.buildForm();

						if (this.route.routeConfig.path.startsWith('new_version/')) {
							this.formGroup.get('version').setValue(this.formGroup.get('version').value + 1);
							this.formGroup.controls['label'].disable();
							this.formGroup.controls['grant'].disable();
							this.isClone = false;
						} else if (this.route.routeConfig.path.startsWith('clone/')) {
							this.formGroup.get('label').setValue(this.dmp.label + " New");
							this.isClone = true;
						}
						const breadCrumbs = [];
						breadCrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.MY-DMPS'), url: "/plans" });
						breadCrumbs.push({ parentComponentName: 'DmpListingComponent', label: this.dmp.label, url: '/plans/clone/' + this.dmp.id });
						this.breadCrumbs = observableOf(breadCrumbs);
					});
			});
	}


	submit() {
		this.saving = true;
		if (this.isClone) {
			this.dmpService.clone(this.formGroup.getRawValue(), this.itemId)
				.pipe(takeUntil(this._destroyed))
				.subscribe(
					complete => this.onCallbackSuccess(),
					error => this.onCallbackError(error)
				);
		} else {
			this.dmpService.newVersion(this.formGroup.getRawValue(), this.itemId)
				.pipe(takeUntil(this._destroyed))
				.subscribe(
					complete => this.onCallbackSuccess(),
					error => this.onCallbackErrorNewVersion(error)
				);
		}
	}

	onCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/plans']);
	}

	onCallbackError(error: any) {
		this.setErrorModel(error.error);
		this.saving = false;
		//this.validateAllFormFields(this.formGroup);
	}

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

	onCallbackErrorNewVersion(errorResponse: HttpErrorResponse) {
		this.uiNotificationService.snackBarNotification(errorResponse.error.message, SnackBarNotificationLevel.Error);
	}


}
