
import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Router } from '@angular/router';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { DmpService } from '@app/core/services/dmp/dmp.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 { 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 { DmpEditorWizardModel } from './dmp-editor-wizard-model';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { LanguageInfo } from '@app/core/model/language-info';
import { LanguageService } from '@app/core/services/language/language.service';
import { LanguageInfoService } from '@app/core/services/culture/language-info-service';


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

	breadCrumbs: Observable<BreadcrumbItem[]> = observableOf([]);

	isNew = true;
	dmp: DmpEditorWizardModel;
	@Input() formGroup: FormGroup;
	@Input() dmpLabel: string;
	@Input() datasetFormGroup: FormGroup;
	private uiNotificationService: UiNotificationService

	profilesAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	filteredProfiles: DatasetProfileModel[];
	filteredProfilesAsync = false;


	constructor(
		public snackBar: MatSnackBar,
		public router: Router,
		private route: ActivatedRoute,
		private _service: DmpService,
		public language: TranslateService,
		private formService: FormService,
		private languageInfoService: LanguageInfoService
	) {
		super();
	}

	ngOnInit(): void {

		this.profilesAutoCompleteConfiguration = {
			filterFn: this.filterProfiles.bind(this),
			initialItems: (extraData) => this.filterProfiles(''),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label'],
			subtitleFn: (item) => item['description']
		};

		if (this.formGroup == null) {
			this.dmp = new DmpEditorWizardModel();
			this.formGroup = this.dmp.buildForm();
		}
		this.formGroup.get('label').setValue(this.language.instant('QUICKWIZARD.CREATE-ADD.CREATE.QUICKWIZARD_CREATE.SECOND-STEP.DMP-NAME') + this.dmpLabel);
		this.formGroup.get('label').setValue(this.language.instant('QUICKWIZARD.CREATE-ADD.CREATE.QUICKWIZARD_CREATE.SECOND-STEP.DMP-NAME') + this.dmpLabel);

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

	formSubmit(): void {
		this.formService.touchAllFormFields(this.formGroup);
		if (!this.isFormValid()) { return; }
		this.onSubmit();
	}

	public isFormValid() {
		return this.formGroup.valid;
	}

	onSubmit(): void {
		// this.grantService.createGrant(this.formGroup.value)
		// 	.pipe(takeUntil(this._destroyed))
		// 	.subscribe(
		// 	complete => this.onCallbackSuccess(),
		// 	error => this.onCallbackError(error)
		// 	);
	}


	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(['/dmp']);
	}

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

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

	filterProfiles(value: string): Observable<DatasetProfileModel[]> {

		this.filteredProfiles = undefined;
		this.filteredProfilesAsync = true;

		const request = new DataTableRequest<DatasetProfileCriteria>(null, null, { fields: ['+label']});
		const criteria = new DatasetProfileCriteria();
		criteria.like = value;
		request.criteria = criteria;
		return this._service.searchDMPProfiles(request);
	}

	datasetIsEmpty() {
		if (this.datasetFormGroup && this.datasetFormGroup.get('datasetsList') && (this.datasetFormGroup.get('datasetsList') as FormArray).length != 0) {
			return true;
		}
		return false;
	}

	getLanguageInfos(): LanguageInfo[] {
		return this.languageInfoService.getLanguageInfoValues();
	}
}
