
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl } from '@angular/forms';
import { DatasetProfileComboBoxType } from '@app/core/common/enum/dataset-profile-combo-box-type';
import { DatasetProfileFieldViewStyle } from '@app/core/common/enum/dataset-profile-field-view-style';
import { DatasetProfileInternalDmpEntitiesType } from '@app/core/common/enum/dataset-profile-internal-dmp-entities-type';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetExternalAutocompleteCriteria } from '@app/core/query/dataset/daatset-external-autocomplete-criteria';
import { DatasetCriteria } from '@app/core/query/dataset/dataset-criteria';
import { DmpCriteria } from '@app/core/query/dmp/dmp-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { ResearcherCriteria } from '@app/core/query/researcher/researcher-criteria';
import { DatasetExternalAutocompleteService } from '@app/core/services/dataset/dataset-external-autocomplete.service';
import { DatasetService } from '@app/core/services/dataset/dataset.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 { VisibilityRulesService } from '@app/ui/misc/dataset-description-form/visibility-rules/visibility-rules.service';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { map, takeUntil } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { ExternalDatasetCriteria } from '@app/core/query/external-dataset/external-dataset-criteria';
import { DataRepositoryCriteria } from '@app/core/query/data-repository/data-repository-criteria';
import { RegistryCriteria } from '@app/core/query/registry/registry-criteria';
import { ServiceCriteria } from '@app/core/query/service/service-criteria';
import { TagCriteria } from '@app/core/query/tag/tag-criteria';
import { isNullOrUndefined } from 'util';
import { ExternalTagEditorModel } from '@app/ui/dataset/dataset-wizard/dataset-wizard-editor.model';
import { MatChipInputEvent } from '@angular/material';
import { ENTER, COMMA } from '@angular/cdk/keycodes';
import { DatasetIdModel } from '@app/core/model/dataset/dataset-id.model';
import { LocalFetchModel } from '@app/core/model/local-fetch/local-fetch.model';
import { CurrencyService } from '@app/core/services/currency/currency.service';

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

	// @Input() field: Field;
	@Input() form: FormGroup;
	@Input() datasetProfileId: any;
	@Input() isChild: Boolean = false;

	// change: Subscription;
	// trackByFn = (index, item) => item ? item['id'] : null;

	public singleAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	public multipleAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	datasetProfileFieldViewStyleEnum = DatasetProfileFieldViewStyle;
	datasetProfileComboBoxTypeEnum = DatasetProfileComboBoxType;
	datasetProfileInternalDmpEntitiesTypeEnum = DatasetProfileInternalDmpEntitiesType;
	externalDatasetAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	dataRepositoriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	registriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	servicesAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	tagsAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;
	currencyAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	readonly separatorKeysCodes: number[] = [ENTER, COMMA];

	tags: ExternalTagEditorModel[] = [];

	datasetIdInitialized: boolean = false;

	readonly datasetIdTypes: any[] = [
		{ name: 'Handle', value: 'handle' },
		{ name: 'DOI', value: 'doi' },
		{ name: 'Ark', value: 'ark' },
		{ name: 'Url', value: 'url' },
		{ name: 'Other', value: 'other' }
	];

	constructor(
		public visibilityRulesService: VisibilityRulesService,
		private datasetExternalAutocompleteService: DatasetExternalAutocompleteService,
		private externalSourcesService: ExternalSourcesService,
		private language: TranslateService,
		private datasetService: DatasetService,
		private dmpService: DmpService,
		private currencyService: CurrencyService
	) { super(); }

	ngOnInit() {
		if (this.form.get('value').value) {
			this.visibilityRulesService.updateValueAndVisibility(this.form.get('id').value, this.form.get('value').value);
		}

		if (this.form.get('viewStyle').value.renderStyle === DatasetProfileFieldViewStyle.ComboBox && this.form.get('data').value.type === DatasetProfileComboBoxType.WordList) {
			if (this.form.get('data').value.multiList) {
				const originalValue = <string>this.form.get('value').value;
				if (originalValue !== null && typeof originalValue === 'string') {
					let values = (<string>this.form.get('value').value).slice(1, -1).split(', ');
					if (!originalValue.startsWith('[') && !originalValue.endsWith(']')) {
						values = undefined;
						values = [originalValue];
					}
					this.form.patchValue({ 'value': values });
					values.forEach(element => {
						this.visibilityRulesService.updateValueAndVisibility(this.form.get('id').value, element);
					});
				}
			}
		}

		// Setup autocomplete configuration if needed
		if (this.form.get('viewStyle').value.renderStyle === DatasetProfileFieldViewStyle.ComboBox && this.form.get('data').value.type === DatasetProfileComboBoxType.Autocomplete) {
			if (!(this.form.controls['data'].value.multiAutoComplete)) {
				this.singleAutoCompleteConfiguration = {
					filterFn: this.searchFromAutocomplete.bind(this),
					initialItems: () => this.searchFromAutocomplete(''),
					displayFn: (item) => (item != null && item.length > 1) ? JSON.parse(item).label : item['label'],
					titleFn: (item) => item['label'],
					valueAssign: (item) => JSON.stringify(item),
					subtitleFn: (item) => item['source'] ? this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-SUBTITLE') + item['source'] : this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-NO-SOURCE')
				};
			}
			else {
				this.multipleAutoCompleteConfiguration = {
					filterFn: this.searchFromAutocomplete.bind(this),
					initialItems: () => this.searchFromAutocomplete(''),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'],
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'],
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item),
					subtitleFn: (item) => item['source'] ? this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-SUBTITLE') + item['source'] : this.language.instant('DATASET-WIZARD.EDITOR.FIELDS.EXTERNAL-AUTOCOMPLETE-NO-SOURCE')
				}
			}
		}

		switch (this.form.get('viewStyle').value.renderStyle) {
			case DatasetProfileFieldViewStyle.ExternalDatasets:
				this.externalDatasetAutoCompleteConfiguration = {
					filterFn: this.searchDatasetExternalDatasets.bind(this),
					initialItems: () => this.searchDatasetExternalDatasets(''),//.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					subtitleFn: (item) => item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.DataRepositories:
				this.dataRepositoriesAutoCompleteConfiguration = {
					filterFn: this.searchDatasetExternalDataRepositories.bind(this),
					initialItems: () => this.searchDatasetExternalDataRepositories(''),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					subtitleFn: (item) => item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.Registries:
				this.registriesAutoCompleteConfiguration = {
					filterFn: this.searchDatasetExternalRegistries.bind(this),
					initialItems: () => this.searchDatasetExternalRegistries(''),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					subtitleFn: (item) => item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.Services:
				this.servicesAutoCompleteConfiguration = {
					filterFn: this.searchDatasetExternalServices.bind(this),
					initialItems: () => this.searchDatasetExternalServices(''),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					subtitleFn: (item) => item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : item.tag ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.tag : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.Tags:
				this.tagsAutoCompleteConfiguration = {
					filterFn: this.filterTags.bind(this),
					initialItems: (excludedItems: any[]) => this.filterTags('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
					displayFn: (item) => this.showTag(item),
					titleFn: (item) => item['name'],
					valueAssign: (item) => this.addTag(item)
				};
				this.parseTags();
				break;
			case DatasetProfileFieldViewStyle.Researchers:
				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) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : 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')),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.Organizations:
				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) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : 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')),
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
			case DatasetProfileFieldViewStyle.DatasetIdentifier:
				const value = this.form.get('value').value;
				this.form.removeControl('value');
				this.form.addControl('value', new DatasetIdModel(value).buildForm());
				this.datasetIdInitialized = true;
				break;
			case DatasetProfileFieldViewStyle.Currency:
				this.currencyAutoCompleteConfiguration = {
					filterFn: this.searchCurrency.bind(this),
					initialItems: () => this.searchCurrency(''),
					displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
					valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item)
				};
				break;
		}

		if (this.form.get('viewStyle').value.renderStyle === DatasetProfileFieldViewStyle.InternalDmpEntities) {
			if (this.form.get('data').value.type === DatasetProfileInternalDmpEntitiesType.Researchers) {
				this.makeAutocompleteConfiguration(this.searchResearchers.bind(this), "name", "tag");
			}
			else if (this.form.get('data').value.type === DatasetProfileInternalDmpEntitiesType.Datasets) {
				this.makeAutocompleteConfiguration(this.searchDatasets.bind(this), "label");
			}
			else if (this.form.get('data').value.type === DatasetProfileInternalDmpEntitiesType.Dmps) {
				this.makeAutocompleteConfiguration(this.searchDmps.bind(this), "label");
			}
		}

		// this.form = this.visibilityRulesService.getFormGroup(this.field.id);
		this.form.get('value').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(item => {
				if (this.form.get('viewStyle').value.renderStyle === DatasetProfileFieldViewStyle.ComboBox && this.form.get('data').value.type === DatasetProfileComboBoxType.WordList && this.form.get('data').value.multiList) {
						item.forEach(element => {
							this.visibilityRulesService.updateValueAndVisibility(this.form.get('id').value, element);
						});

				} else {
					this.visibilityRulesService.updateValueAndVisibility(this.form.get('id').value, item);
				}
			});
	}

	// _optionRemove(event) {
	// 	const array = JSON.parse(this.form.get('value').value);
	// 	if (array) {
	// 		const index = array.map(x => x.id).indexOf(event.id);
	// 		if (index >= 0) {
	// 			array.splice(index, 1);
	// 		}
	// 		this.form.get('value').patchValue(JSON.stringify(array));
	// 	}
	// }

	searchFromAutocomplete(query: string) {
		const autocompleteRequestItem: RequestItem<DatasetExternalAutocompleteCriteria> = new RequestItem();
		autocompleteRequestItem.criteria = new DatasetExternalAutocompleteCriteria();

		autocompleteRequestItem.criteria.fieldID = this.form.get('id').value;
		if (typeof this.datasetProfileId === 'string') {
			autocompleteRequestItem.criteria.profileID = this.datasetProfileId;
		} else {
			autocompleteRequestItem.criteria.profileID = this.datasetProfileId.id;
		}
		autocompleteRequestItem.criteria.like = query;
		return this.datasetExternalAutocompleteService.queryAutocomplete(autocompleteRequestItem);
	}

	searchResearchers(query: string) {
		const reasearcherAutocompleteRequestItem: RequestItem<ResearcherCriteria> = new RequestItem();
		reasearcherAutocompleteRequestItem.criteria = new ResearcherCriteria;
		reasearcherAutocompleteRequestItem.criteria.name = query;
		return this.externalSourcesService.searchDMPResearchers(reasearcherAutocompleteRequestItem);
	}

	searchDatasets(query: string) {
		let fields: Array<string> = new Array();
		const datasetsAutocompleteRequestItem: DataTableRequest<DatasetCriteria> = new DataTableRequest(0, 25, { fields: fields });
		datasetsAutocompleteRequestItem.criteria = new DatasetCriteria();
		datasetsAutocompleteRequestItem.criteria.like = query;
		return this.datasetService.getPaged(datasetsAutocompleteRequestItem).pipe(map(item => item.data));
	}

	searchDmps(query: string) {
		let fields: Array<string> = new Array();
		const dmpsAutocompleteRequestItem: DataTableRequest<DmpCriteria> = new DataTableRequest(0, 25, { fields: fields });
		dmpsAutocompleteRequestItem.criteria = new DmpCriteria();
		dmpsAutocompleteRequestItem.criteria.like = query;
		return this.dmpService.getPaged(dmpsAutocompleteRequestItem).pipe(map(item => item.data));
	}

	makeAutocompleteConfiguration(myfunc: Function, title: string, subtitle?: string): void {
		if (!(this.form.controls['data'].value.multiAutoComplete)) {
			this.singleAutoCompleteConfiguration = {
				filterFn: myfunc.bind(this),
				initialItems: (extraData) => myfunc(''),
				displayFn: (item) => (item != null && item.length > 1) ? JSON.parse(item)[title] : item[title],
				titleFn: (item) => item[title],
				valueAssign: (item) => JSON.stringify(item),
				subtitleFn: (item) => item[subtitle]
			};
		}
		else {
			this.multipleAutoCompleteConfiguration = {
				filterFn: myfunc.bind(this),
				initialItems: (extraData) => myfunc(''),
				displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'],
				titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['label'] : item['label'],
				valueAssign: (item) => typeof (item) == 'string' ? item : JSON.stringify(item),
				subtitleFn: (item) => item[subtitle]
			}
		}
	}

	searchDatasetExternalDatasets(query: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<ExternalDatasetCriteria> = new RequestItem();
		requestItem.criteria = new ExternalDatasetCriteria();
		requestItem.criteria.like = query;
		requestItem.criteria.type = '';
		return this.externalSourcesService.searchDatasetSExternalDatasetservice(requestItem);
	}

	searchDatasetExternalDataRepositories(query: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<DataRepositoryCriteria> = new RequestItem();
		requestItem.criteria = new DataRepositoryCriteria();
		requestItem.criteria.like = query;
		requestItem.criteria.type = '';
		return this.externalSourcesService.searchDatasetRepository(requestItem);
	}

	searchDatasetExternalRegistries(query: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<RegistryCriteria> = new RequestItem();
		requestItem.criteria = new RegistryCriteria();
		requestItem.criteria.like = query;
		requestItem.criteria.type = '';
		return this.externalSourcesService.searchDatasetRegistry(requestItem);
	}

	searchDatasetExternalServices(query: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<ServiceCriteria> = new RequestItem();
		requestItem.criteria = new ServiceCriteria();
		requestItem.criteria.like = query;
		requestItem.criteria.type = '';
		return this.externalSourcesService.searchDatasetService(requestItem);
	}

	searchDatasetTags(query: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<TagCriteria> = new RequestItem();
		requestItem.criteria = new TagCriteria();
		requestItem.criteria.like = query;
		requestItem.criteria.type = '';
		return this.externalSourcesService.searchDatasetTags(requestItem);
	}

	parseTags() {
		let stringValue = this.form.get('value').value;
		if (typeof stringValue === 'string') {
			stringValue = (<string>stringValue).replace(new RegExp('{', 'g'), '{"').replace(new RegExp('=', 'g'), '":"').replace(new RegExp(',', 'g'), '",').replace(new RegExp(', ', 'g'), ', "').replace(new RegExp('}', 'g'), '"}');
			stringValue = stringValue.replace(new RegExp('}"', 'g'), '}').replace(new RegExp('"{', 'g'), '{');
		} else if (stringValue instanceof Array) {
			const tempArray = new Array();
			for (let stringTag of stringValue) {
				tempArray.push(JSON.parse(stringTag));
			}
			stringValue = JSON.stringify(tempArray);
		}
		const tagArray = JSON.parse(stringValue);
		this.form.patchValue({'value': tagArray});
	}

	filterTags(value: string): Observable<ExternalSourceItemModel[]> {
		const requestItem: RequestItem<TagCriteria> = new RequestItem();
		const criteria: TagCriteria = new TagCriteria();
		criteria.like = value;
		requestItem.criteria = criteria;
		return this.externalSourcesService.searchDatasetTags(requestItem);
	}

	showTag(ev: any) {
		if (typeof ev === 'string') {
			return ev;
		} else {
			return ev.name;
		}
	}

	addTag(ev: any) {
		let item: ExternalTagEditorModel;
		//this.filteredTags = this.formGroup.get('tags').value;
		if (typeof ev === 'string') {
			item = new ExternalTagEditorModel('', ev);
		} else {
			item = ev;
		}
		if (item.name !== '' ) {
			return 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 } });
	}

	getDatasetIdControl(name: string): FormControl {
		return this.form.get('value').get(name) as FormControl;
	}

	searchCurrency(query: string): Observable<LocalFetchModel[]> {
		return this.currencyService.get(query);
	}
}
