
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormArray } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DmpProfileDefinition } from '@app/core/model/dmp-profile/dmp-profile';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { DmpProfileCriteria } from '@app/core/query/dmp/dmp-profile-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { DmpProfileService } from '@app/core/services/dmp/dmp-profile.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.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 { AddResearcherComponent } from '@app/ui/dmp/editor/add-researcher/add-researcher.component';
import { AvailableProfilesComponent } from '@app/ui/dmp/editor/available-profiles/available-profiles.component';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { AddOrganizationComponent } from '../add-organization/add-organization.component';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
import { LanguageInfoService } from '@app/core/services/culture/language-info-service';
import { LanguageInfo } from '@app/core/model/language-info';
import { LicenseCriteria } from '@app/core/query/license/license-criteria';
import { AddCostComponent } from '../cost-editor/add-cost/add-cost.component';
import { CostEditorModel } from '../cost-editor/add-cost/add-cost.model';

interface Visible {
	value: boolean;
	name: string;
}

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

	@Input() formGroup: FormGroup = null;
	@Input() isNewVersion: boolean;
	@Input() isUserOwner: boolean;
	@Input() isClone: boolean;

	profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		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'],
		subtitleFn: (item) => item['description'],
		popupItemActionIcon: 'visibility'
	};

	organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		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'],
		subtitleFn: (item) => item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
	};
	researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		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'],
		subtitleFn: (item) => item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
	};
	dmpProfileAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.dmpProfileSearch.bind(this),
		initialItems: (extraData) => this.dmpProfileSearch(''),
		displayFn: (item) => item['label'],
		titleFn: (item) => item['label']
	};

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

	selectedDmpProfileDefinition: DmpProfileDefinition;

	visibles: Visible[] = [
		{ value: true, name: 'DMP-EDITOR.VISIBILITY.PUBLIC' },
		{ value: false, name: 'DMP-EDITOR.VISIBILITY.RESTRICTED' }
	]

	constructor(
		private dmpProfileService: DmpProfileService,
		private externalSourcesService: ExternalSourcesService,
		private _service: DmpService,
		private dialog: MatDialog,
		private language: TranslateService,
		private configurationService: ConfigurationService,
		private languageInfoService: LanguageInfoService
	) {
		super();
	}

	ngOnInit() {
		if (this.formGroup.get('definition')) { this.selectedDmpProfileDefinition = this.formGroup.get('definition').value; }
		this.registerFormEventsForDmpProfile();

		if (this.isNewVersion) {
			this.formGroup.get('label').disable();
		}

		if (!this.isUserOwner && !this.isClone) {
			this.formGroup.disable();
		}
		if (isNullOrUndefined(this.formGroup.get('extraProperties').get('publicDate').value)) {
			this.formGroup.get('extraProperties').get('publicDate').patchValue(new Date());
		}
	}

	registerFormEventsForDmpProfile(definitionProperties?: DmpProfileDefinition): void {
		this.formGroup.get('profile').valueChanges
			.pipe(
				takeUntil(this._destroyed))
			.subscribe(Option => {
				if (Option instanceof Object) {
					this.selectedDmpProfileDefinition = null;
					this.dmpProfileService.getSingle(Option.id)
						.pipe(takeUntil(this._destroyed))
						.subscribe(result => {
							this.selectedDmpProfileDefinition = result.definition;
						});
				} else {
					this.selectedDmpProfileDefinition = null;
				}
				this.selectedDmpProfileDefinition = definitionProperties;
			})
	}

	dmpProfileSearch(query: string) {
		let fields: Array<string> = new Array();
		var request = new DataTableRequest<DmpProfileCriteria>(0, 10, { fields: fields });
		request.criteria = new DmpProfileCriteria();
		return this.dmpProfileService.getPaged(request).pipe(map(x => x.data));
	}

	licenseSearch(query: string): Observable<ExternalSourceItemModel[]> {
		const request = new RequestItem<LicenseCriteria>();
		request.criteria = new LicenseCriteria();
		request.criteria.like = query;
		request.criteria.type = '';
		return this.externalSourcesService.searchLicense(request);
	}

	// 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) {
	// 	this.setErrorModel(error.error);

	// 	//this.validateAllFormFields(this.formGroup);
	// }

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

	filterOrganisations(value: string): Observable<ExternalSourceItemModel[]> {
		return this.externalSourcesService.searchDMPOrganizations(value);
	}

	filterResearchers(value: string): Observable<ExternalSourceItemModel[]> {
		return this.externalSourcesService.searchDMPResearchers({ criteria: { name: value, like: null } });
	}

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

	addResearcher(event: MouseEvent) {
		event.stopPropagation();
		const dialogRef = this.dialog.open(AddResearcherComponent, {
			data: this.formGroup.get('researchers')
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				const fullName = result.firstName + " " + result.lastName;
				const newItem = {
					label: null,
					name: fullName,
					id: null,
					status: 0,
					key: "Internal",
					reference: result.reference
				};
				const researchersArray = this.formGroup.get('researchers').value || [];
				researchersArray.push(newItem);
				this.formGroup.get('researchers').setValue(researchersArray);
			}
		});
	}

	addOrganization(event: MouseEvent) {
		event.stopPropagation();
		const dialogRef = this.dialog.open(AddOrganizationComponent, {
			data: this.formGroup.get('organisations')
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				const fullName = result.name;
				const newItem = {
					label: null,
					name: fullName,
					id: null,
					status: 0,
					key: "Internal",
				};
				const organizationsArray = this.formGroup.get('organisations').value || [];
				organizationsArray.push(newItem);
				this.formGroup.get('organisations').setValue(organizationsArray);
			}
		});
	}

	showOrganizationCreator(): boolean {
		return this.configurationService.allowOrganizationCreator;
	}

	canAddOrganizations(): boolean {
		if (!isNullOrUndefined(this.formGroup.get('organizations'))) {
			return this.formGroup.get('organiztions').disabled;
		} else {
			return false;
		}
	}

	availableProfiles(event: MouseEvent) {
		event.stopPropagation();
		const dialogRef = this.dialog.open(AvailableProfilesComponent, {
			data: {
				profiles: this.formGroup.get('profiles')
			}
		});

		return false;
	}

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

	getAssociates(): any[] {
		let associates: any[] = [];
		//associates = (this.formGroup.get('researchers').value as any[]);
		associates = associates.concat(this.formGroup.get('associatedUsers').value);
		return associates;
	}

	addCost(event: MouseEvent) {
		event.stopPropagation();
		const dialogRef = this.dialog.open(AddCostComponent, {
			data: this.formGroup.get('extraProperties').get('costs')
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				const costsArray = this.formGroup.get('extraProperties').get('costs').value || [];
				costsArray.push(result);
				let costeditModel: CostEditorModel = new CostEditorModel();
				costeditModel = costeditModel.fromModel(result);
				(<FormArray>this.formGroup.get('extraProperties').get('costs')).push(costeditModel.buildForm(null, true));
			}
		});
	}
}
