import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { ExternalSourcesConfiguration } from '@app/core/model/external-sources/external-sources-configuration';
import { DataRepositoryCriteria } from '@app/core/query/data-repository/data-repository-criteria';
import { ExternalDatasetCriteria } from '@app/core/query/external-dataset/external-dataset-criteria';
import { RegistryCriteria } from '@app/core/query/registry/registry-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { ServiceCriteria } from '@app/core/query/service/service-criteria';
import { TagCriteria } from '@app/core/query/tag/tag-criteria';
import { ExternalSourcesConfigurationService } from '@app/core/services/external-sources/external-sources-configuration.service';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { ExternalDataRepositoryEditorModel, ExternalDatasetEditorModel, ExternalRegistryEditorModel, ExternalServiceEditorModel, ExternalTagEditorModel } from '@app/ui/dataset/dataset-wizard/dataset-wizard-editor.model';
import { DatasetExternalDataRepositoryDialogEditorComponent } from '@app/ui/dataset/dataset-wizard/external-references/editors/data-repository/dataset-external-data-repository-dialog-editor.component';
import { DatasetExternalDatasetDialogEditorComponent } from '@app/ui/dataset/dataset-wizard/external-references/editors/external-dataset/dataset-external-dataset-dialog-editor.component';
import { DatasetExternalRegistryDialogEditorComponent } from '@app/ui/dataset/dataset-wizard/external-references/editors/registry/dataset-external-registry-dialog-editor.component';
import { DatasetExternalServiceDialogEditorComponent } from '@app/ui/dataset/dataset-wizard/external-references/editors/service/dataset-external-service-dialog-editor.component';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { takeUntil, map } from 'rxjs/operators';
import { ENTER, COMMA } from '@angular/cdk/keycodes';
import { MatChipInputEvent } from '@angular/material/chips';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { ExternalDataRepositoryService } from '@app/core/services/external-sources/data-repository/extternal-data-repository.service';
import { ExternalDatasetService } from '@app/core/services/external-sources/dataset/external-dataset.service';
import { ExternalRegistryService } from '@app/core/services/external-sources/registry/external-registry.service';
import { ExternalServiceService } from '@app/core/services/external-sources/service/external-service.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';

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

	@Input() formGroup: FormGroup = null;
	@Input() viewOnly = false;
	@Output() formChanged: EventEmitter<any> = new EventEmitter();

	public filteringTagsAsync = false;
	public filteredTags: ExternalSourceItemModel[];

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

	externalDatasetAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchDatasetExternalDatasets.bind(this),
		initialItems: (type) => this.searchDatasetExternalDatasets('', type),//.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1),
		displayFn: (item) => item ? item.name : null,
		titleFn: (item) => item ? item.name : null,
		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')
	};

	registriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchDatasetExternalRegistries.bind(this),
		initialItems: (type) => this.searchDatasetExternalRegistries('', type),
		displayFn: (item) => item ? item.name : null,
		titleFn: (item) => item ? item.name : null,
		subtitleFn: (item) => item.source ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item.source : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')
	};

	dataRepositoriesAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchDatasetExternalDataRepositories.bind(this),
		initialItems: (type) => this.searchDatasetExternalDataRepositories('', type),
		displayFn: (item) => item ? item.name : null,
		titleFn: (item) => item ? item.name : null,
		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')
	};

	servicesAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchDatasetExternalServices.bind(this),
		initialItems: (type) => this.searchDatasetExternalServices('', type),
		displayFn: (item) => item ? item.label : null,
		titleFn: (item) => item ? item.label : null,
		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')
	};

	tagsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		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)
	};

	externalSourcesConfiguration: ExternalSourcesConfiguration;

	// new AutoCompleteConfiguration(this.externalSourcesService.searchDatasetRepository.bind(this.externalSourcesService),

	constructor(
		private dialog: MatDialog,
		private router: Router,
		private language: TranslateService,
		private externalSourcesService: ExternalSourcesService,
		private externalSourcesConfigurationService: ExternalSourcesConfigurationService,
		private externalDataRepositoryService: ExternalDataRepositoryService,
		private externalDatasetService: ExternalDatasetService,
		private externalRegistryService: ExternalRegistryService,
		private externalServiceService: ExternalServiceService,
	) { super(); }

	ngOnInit() {

		this.externalSourcesConfigurationService.getExternalSourcesConfiguration()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				this.externalSourcesConfiguration = result;
				this.externalSourcesConfiguration.dataRepositories.push({ key: '', label: 'All' });
				this.externalSourcesConfiguration.externalDatasets.push({ key: '', label: 'All' });
				this.externalSourcesConfiguration.registries.push({ key: '', label: 'All' });
				this.externalSourcesConfiguration.services.push({ key: '', label: 'All' });
				if (!isNullOrUndefined(this.externalSourcesConfiguration.tags)) {
					this.externalSourcesConfiguration.tags.push({ key: '', label: 'All' });
				} else {
					this.externalSourcesConfiguration.tags = [{ key: '', label: 'All' }];
				}
			});

		this.formGroup.valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(val => {
				this.formChanged.emit(val);
			});
	}

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

	externalDatasetsOnItemChange(event) {
		const externalDatasetModel = new ExternalDatasetEditorModel(event.id, event.abbreviation, event.name, event.pid ? event.pid : event.reference, event.source);
		(<FormArray>this.formGroup.get('externalDatasets')).push(externalDatasetModel.buildForm());
	}

	registriesOnItemChange(event) {
		const registryModel = new ExternalRegistryEditorModel(event.abbreviation, event.definition, event.id, event.name, event.pid ? event.pid : event.reference, event.uri, event.source);
		(<FormArray>this.formGroup.get('registries')).push(registryModel.buildForm());
	}

	servicesOnItemChange(event) {
		const serviceModel = new ExternalServiceEditorModel(event.abbreviation, event.definition, event.id, event.label, event.reference, event.uri);
		(<FormArray>this.formGroup.get('services')).push(serviceModel.buildForm());
	}

	tagsOnItemChange(event) {
		const tagModel = new ExternalTagEditorModel(event.id, event.name);
		(<FormArray>this.formGroup.get('tags')).push(tagModel.buildForm());
	}


	dataRepositoriesOnItemChange(event) {
		const dataRepositoryModel = new ExternalDataRepositoryEditorModel(event.id, event.name, event.abbreviation, event.uri, event.pid, event.source);
		(<FormArray>this.formGroup.get('dataRepositories')).push(dataRepositoryModel.buildForm());
	}

	addDataRepository() {
		const dialogRef = this.dialog.open(DatasetExternalDataRepositoryDialogEditorComponent, {
			width: '500px',
			restoreFocus: false,
			data: {}
		});
		dialogRef.afterClosed()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (!result) { return; }
				const dataRepositoryModel = new ExternalDataRepositoryEditorModel(result.id, result.name, result.abbreviation, result.uri, result.pid, result.source);
				(<FormArray>this.formGroup.get('dataRepositories')).push(dataRepositoryModel.buildForm());
			});
	}

	addRegistry() {
		const dialogRef = this.dialog.open(DatasetExternalRegistryDialogEditorComponent, {
			width: '500px',
			restoreFocus: false,
			data: {}
		});
		dialogRef.afterClosed()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (!result) { return; }
				const registryModel = new ExternalRegistryEditorModel(result.abbreviation, result.definition, result.id, result.label, result.reference, result.uri, result.source);
				(<FormArray>this.formGroup.get('registries')).push(registryModel.buildForm());
			});
	}

	addExternalDataset() {
		const dialogRef = this.dialog.open(DatasetExternalDatasetDialogEditorComponent, {
			width: '500px',
			restoreFocus: false,
			data: {}
		});
		dialogRef.afterClosed()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (!result) { return; }
				const externalDatasetModel = new ExternalDatasetEditorModel(result.id, result.abbreviation, result.name, result.reference, result.source);
				(<FormArray>this.formGroup.get('externalDatasets')).push(externalDatasetModel.buildForm());
			});
	}

	addService() {
		const dialogRef = this.dialog.open(DatasetExternalServiceDialogEditorComponent, {
			width: '500px',
			restoreFocus: false,
			data: {}
		});
		dialogRef.afterClosed()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (!result) { return; }
				const serviceModel = new ExternalServiceEditorModel(result.abbreviation, result.definition, result.id, result.label, result.reference, result.uri, result.source);
				(<FormArray>this.formGroup.get('services')).push(serviceModel.buildForm());
			});
	}

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

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

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

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

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

	removeTag(tag: any) {
		(<FormArray>this.formGroup.get('tags')).removeAt(((<FormArray>this.formGroup.get('tags')).value as any[]).indexOf(tag));
	}

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

	isInternal(element: any): boolean {
		if (element.get('source') == null) {
			// console.log(element);
		}
		return element.get('source').value === 'Internal';
	}

	updateDataRepository(dataRepository: FormGroup) {
		this.externalDataRepositoryService.create(dataRepository.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				(result) => {
					dataRepository.setValue(result);
				}
			);
	}

	updateExternalDataset(externalDataset: FormGroup) {
		this.externalDatasetService.create(externalDataset.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				(result) => {
					externalDataset.setValue(result);
				}
			);
	}

	updateRegistry(registry: FormGroup) {
		this.externalRegistryService.create(registry.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				(result) => {
					registry.setValue(result);
				}
			);
	}

	updateService(service: FormGroup) {
		this.externalServiceService.create(service.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				(result) => {
					service.setValue(result);
				}
			);
	}

	filterTags(value: string): Observable<ExternalSourceItemModel[]> {
		this.filteringTagsAsync = true;

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