
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { GrantService } from '@app/core/services/grant/grant.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { GrantEditorWizardModel } from '@app/ui/quick-wizard/grant-editor/grant-editor-wizard-model';
import { BaseComponent } from '@common/base/base.component';
import { FormService } from '@common/forms/form-service';
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 { takeUntil } from 'rxjs/operators';
import { strict } from 'assert';

@Component({
	selector: 'app-quick-wizard-grant-editor-component',
	templateUrl: 'grant-editor-wizard.component.html',
	styleUrls: ['./grant-editor-wizard.component.scss']
})
export class GrantEditorWizardComponent extends BaseComponent implements OnInit, IBreadCrumbComponent {
	breadCrumbs: Observable<BreadcrumbItem[]> = observableOf([]);

	isNew = false;
	grant: GrantEditorWizardModel;
	@Input() grantformGroup: FormGroup;
	@Input() funderFormGroup: FormGroup;
	private uiNotificationService: UiNotificationService

	grantAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	constructor(
		public snackBar: MatSnackBar,
		public router: Router,
		public language: TranslateService,
		private grantService: GrantService,
		private formService: FormService
	) {
		super();
	}

	getGrantIdText(item) {
		if (item.reference != null && typeof item.reference == 'string') {
			const parts = (item.reference as String).split('::');
			return parts.length > 1 ? ' (' + parts[parts.length - 1] + ')' : '';
		}
		return '';
	}

	ngOnInit() {
		this.breadCrumbs = observableOf([{
			parentComponentName: 'QuickCreate',
			label: this.language.instant('NAV-BAR.GRANT'),
			url: '/quick-wizard/grant'
		}]);

		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();

		this.grantAutoCompleteConfiguration = {
			filterFn: this.searchGrant.bind(this),
			initialItems: (extraData) => this.searchGrant(''),
			displayFn: (item) => item['label'] + this.getGrantIdText(item),
			titleFn: (item) => item['label'] + this.getGrantIdText(item),
			subtitleFn: (item) => item['source'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['source'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
		};

		if (this.funderFormGroup && this.funderFormGroup.valid) {
			this.grantformGroup.get('existGrant').enable();
			this.grantformGroup.get('label').disable();
			this.grantformGroup.get('description').disable();
		} else {
			this.grantformGroup.get('existGrant').disable();
		}

		this.funderFormGroup.statusChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.grantformGroup.reset();
				if (x == 'INVALID') {
					this.grantformGroup.get('existGrant').reset();
					this.grantformGroup.get('label').reset();
					this.grantformGroup.get('description').reset();
					this.grantformGroup.get('existGrant').disable();
					this.grantformGroup.get('label').disable();
					this.grantformGroup.get('description').disable();
				} else if (x == 'VALID') {
					if (!this.isNew) {
						this.grantformGroup.get('label').reset();
						this.grantformGroup.get('description').reset();
						this.grantformGroup.get('label').disable();
						this.grantformGroup.get('description').disable();
						this.grantformGroup.get('existGrant').enable();

					}
				}
			})
	}

	isFunderFormInvalid() {
		return !this.funderFormGroup.valid;
	}

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

	onCallbackError(errorResponse: any) {
		this.setErrorModel(errorResponse.error.payload);
		this.formService.validateAllFormFields(this.grantformGroup);
	}

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

	searchGrant(query: string) {
		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		if (this.funderFormGroup.get('existFunder').value) {
			grantRequestItem.criteria.funderReference = this.funderFormGroup.controls['existFunder'].value.reference;
		}
		return this.grantService.getWithExternal(grantRequestItem);
	}

	create() {
		this.isNew = !this.isNew;
		if (this.isNew) {
			this.grantformGroup.get('existGrant').reset();
			this.grantformGroup.get('existGrant').disable();
			this.grantformGroup.get('label').enable();
			this.grantformGroup.get('description').enable();
		} else {
			this.grantformGroup.get('label').reset();
			this.grantformGroup.get('label').disable();
			this.grantformGroup.get('description').reset();
			this.grantformGroup.get('description').disable();
			this.grantformGroup.get('existGrant').enable();
		}
	}
}
