
import { Component, Input, OnInit } from '@angular/core';
import { 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 { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { UserModel } from '@app/core/model/user/user';
import { BaseCriteria } from '@app/core/query/base-criteria';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { DataTableData } from '@app/core/model/data-table/data-table-data';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';

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

	isNew = true;
	@Input() formGroup: FormGroup = null;

	filteringOrganisationsAsync = false;
	filteringResearchersAsync = false;
	filteredProfilesAsync = false;
	filteredOrganisations: ExternalSourceItemModel[];
	filteredResearchers: ExternalSourceItemModel[];
	filteredProfiles: DatasetProfileModel[];

	grantAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	createNewVersion;
	associatedUsers: Array<UserModel>;
	labelDisabled = false;

	constructor(
		private dataManagementPlanService: DmpService,
		private grantService: GrantService,
		private externalSourcesService: ExternalSourcesService,
		private route: ActivatedRoute,
		public snackBar: MatSnackBar,
		public router: Router,
		public language: TranslateService,
		private _service: DmpService,
		private uiNotificationService: UiNotificationService
	) {
		super();
	}

	ngOnInit() {

		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();
		this.grantAutoCompleteConfiguration = {
			filterFn: this.searchGrant.bind(this.grantService),
			initialItems: () => this.searchGrant(''),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label']
		};

		this.profilesAutoCompleteConfiguration = {
			filterFn: this.filterProfiles.bind(this),
			initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label'],
			popupItemActionIcon: 'visibility'
		};

		this.organisationsAutoCompleteConfiguration = {
			filterFn: this.filterOrganisations.bind(this),
			initialItems: (excludedItems: any[]) => this.filterOrganisations('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
			displayFn: (item) => item['name'],
			titleFn: (item) => item['name']
		};

		this.researchersAutoCompleteConfiguration = {
			filterFn: this.filterResearchers.bind(this),
			initialItems: (excludedItems: any[]) => this.filterResearchers('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
			displayFn: (item) => item['name'],
			titleFn: (item) => item['name']
		};

		const organisationRequestItem: RequestItem<BaseCriteria> = new RequestItem();
		organisationRequestItem.criteria = new BaseCriteria();

		this.route.data
			.pipe(takeUntil(this._destroyed))
			.subscribe(value => {
				this.formGroup.controls['version'].disable();
			});
	}

	searchGrant(query: string) {
		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		return this.grantService.getWithExternal(grantRequestItem);
	}

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

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

	onSubmit(): void {
		this.dataManagementPlanService.createDmp(this.formGroup.getRawValue())
			.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(['/plans']);
	}

	onCallbackError(error: any) {

	}

	availableProfiles() { }

	addResearcher() { }

	public cancel(): void {
		this.router.navigate(['/plans']);
	}

	filterOrganisations(value: string): Observable<ExternalSourceItemModel[]> {

		this.filteredOrganisations = undefined;
		this.filteringOrganisationsAsync = true;

		return this.externalSourcesService.searchDMPOrganizations(value);
	}

	filterResearchers(value: string): Observable<ExternalSourceItemModel[]> {

		this.filteredResearchers = undefined;
		this.filteringResearchersAsync = true;

		return this.externalSourcesService.searchDMPResearchers({ criteria: { name: value, like: null } });
	}

	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);
	}

}
