
import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { MatAccordion } from '@angular/material/expansion';
import { ActivatedRoute } from '@angular/router';
import { GrantStateType } from '@app/core/common/enum/grant-state-type';
import { DataTableData } from '@app/core/model/data-table/data-table-data';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { GrantListingModel } from '@app/core/model/grant/grant-listing';
import { OrganizationModel } from '@app/core/model/organisation/organization';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { ExploreDatasetCriteriaModel } from '@app/core/query/explore-dataset/explore-dataset-criteria';
import { ExploreDmpCriteriaModel } from '@app/core/query/explore-dmp/explore-dmp-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { OrganisationCriteria } from '@app/core/query/organisation/organisation-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { TagCriteria } from '@app/core/query/tag/tag-criteria';
import { AuthService } from '@app/core/services/auth/auth.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 { GrantService } from '@app/core/services/grant/grant.service';
import { OrganisationService } from '@app/core/services/organisation/organisation.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs';
import { map } from 'rxjs/operators';


@Component({
	selector: 'app-explore-dataset-filters-component',
	templateUrl: './explore-dataset-filters.component.html',
	styleUrls: ['./explore-dataset-filters.component.scss']
})
export class ExploreDatasetFiltersComponent extends BaseComponent implements OnInit, AfterViewInit {

	@Input() facetCriteria = new ExploreDatasetCriteriaModel();
	@Output() facetCriteriaChange = new EventEmitter();
	public filteringTagsAsync = false;
	public filteredTags: ExternalSourceItemModel[];
	GrantStateType = GrantStateType;
	grants: Observable<GrantListingModel[]>;
	profiles: Observable<DatasetProfileModel[]>;
	dmpOrganisations: Observable<ExternalSourceItemModel[]>;
	dmpIds: Observable<DataTableData<DmpListingModel>>;
	grantOptions: Observable<GrantListingModel[]>;
	grantStateOptions: Observable<any[]>;
	filteringOrganisationsAsync = false;
	@ViewChild('facetAccordion', { static: false }) accordion: MatAccordion;

	displayGrantStateValue = (option) => option['value'];
	displayGrantStateLabel = (option) => option['label'];

	displayGrantValue = (option) => option['id'];
	displayGrantLabel = (option) => option['label'];

	displayProfileValue = (option) => option['id'];
	displayProfileLabel = (option) => option['label'];

	displayDmpOrganisationsValue = (option) => option['id'];
	displayDmpOrganisationsLabel = (option) => option['name'];

	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) => item['name'],
		titleFn: (item) => item['name']
	};

	dmpAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		filterFn: (x, excluded) => this.filterDmps(x).pipe(map(x => x.data)),
		initialItems: (extraData) => this.filterDmps('').pipe(map(x => x.data)),
		displayFn: (item) => item['label'],
		titleFn: (item) => item['label']
	};

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

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

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

	constructor(
		public activatedRoute: ActivatedRoute,
		private authentication: AuthService,
		public grantService: GrantService,
		public dmpService: DmpService,
		public organisationService: OrganisationService,
		public languageService: TranslateService,
		public datasetProfileService: DatasetService,
		public externalSourcesService: ExternalSourcesService,
	) { super(); }

	ngOnInit() {
		setTimeout(() => {
			this.grantStateOptions = observableOf(
				[
					{ label: this.languageService.instant('FACET-SEARCH.GRANT-STATUS.OPTIONS.INACTIVE'), value: GrantStateType.Finished },
					{ label: this.languageService.instant('FACET-SEARCH.GRANT-STATUS.OPTIONS.ACTIVE'), value: GrantStateType.OnGoing },
				]);
		});
		// this.profiles = this.datasetProfileService.getDatasetProfiles();
		this.dmpOrganisations = this.externalSourcesService.searchDMPOrganizations('');
	}

	ngAfterViewInit(): void {
		// this.accordion.openAll();
	}

	public grantStatusChanged(event) {
		this.facetCriteria.grantStatus = event.value;
		if (event.value === 'null') {
			this.facetCriteria.grantStatus = null;
			this.grants = observableOf([]);
			this.facetCriteria.grants = [];
		}
		// if (event.option.selected) {
		// if (event.source.checked) {
		else {
			// const grantCriteria = new GrantCriteria();
			// grantCriteria.grantStateType = this.facetCriteria.grantStatus;
			//grantCriteria['length'] = 10;
			const fields: Array<string> = new Array<string>();
			fields.push('asc');
			const dataTableRequest: DataTableRequest<GrantCriteria> = new DataTableRequest(0, null, { fields: fields });
			dataTableRequest.criteria = new GrantCriteria();
			dataTableRequest.criteria.grantStateType = this.facetCriteria.grantStatus;
			dataTableRequest.criteria['length'] = 10;

			this.grants = this.grantService.getPublicPaged(dataTableRequest).pipe(map(x => x.data));
			this.facetCriteria.grants = [];
		}
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	public grantChanged(event: any) {
		const eventValue = event.option.value.id;
		if (event.option.selected) { this.facetCriteria.grants.push(eventValue); }
		if (!event.option.selected) {
			const index = this.facetCriteria.grants.indexOf(eventValue);
			this.facetCriteria.grants.splice(index, 1);
		}
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	removeGrant(grant) {
		this.facetCriteria.grants.splice(this.facetCriteria.grants.indexOf(grant), 1);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	public profileChanged(event: any) {
		const eventValue = event.option.value.id;
		if (event.option.selected) {
			this.facetCriteria.datasetProfile.push(eventValue);
		}
		if (!event.option.selected) {
			const index = this.facetCriteria.datasetProfile.indexOf(eventValue);
			this.facetCriteria.datasetProfile.splice(index, 1);
		}
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	// getProfiles() {
	// 	return this.datasetProfileService.getDatasetProfiles();
	// }

	removeProfile(profile) {
		this.facetCriteria.datasetProfile.splice(this.facetCriteria.datasetProfile.indexOf(profile), 1);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	getOrganisations() {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const dataTableRequest: DataTableRequest<OrganisationCriteria> = new DataTableRequest(0, null, { fields: fields });
		dataTableRequest.criteria = new OrganisationCriteria();
		dataTableRequest.criteria.labelLike = '';
		return this.organisationService.searchPublicOrganisations(dataTableRequest).pipe(map(x => x.data));
	}

	public roleChanged(event: any) {
		this.facetCriteria.role = event.value;
		if (event.value === 'null') {
			this.facetCriteria.role = null;
		}
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	public dmpOrganisationChanged(event: any) {
		const eventValue = event.option.value.id;
		if (event.option.selected) { this.facetCriteria.dmpOrganisations.push(eventValue); }
		if (!event.option.selected) {
			const index = this.facetCriteria.dmpOrganisations.indexOf(eventValue);
			this.facetCriteria.dmpOrganisations.splice(index, 1);
		}
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	public grantSearch(value: string): Observable<GrantListingModel[]> {

		const grantCriteria = new GrantCriteria();
		grantCriteria.grantStateType = this.facetCriteria.grantStatus;
		grantCriteria['length'] = 10;
		grantCriteria.like = value;

		const fields: Array<string> = new Array<string>();
		fields.push('asc');

		const dataTableRequest: DataTableRequest<GrantCriteria> = new DataTableRequest(0, null, { fields: fields });
		dataTableRequest.criteria = grantCriteria;
		//const dataTableRequest: RequestItem<GrantCriteria> = { criteria: grantCriteria };
		//return this.grantService.getPaged(dataTableRequest, "autocomplete").map(x => x.data);
		return this.grantService.getPublicPaged(dataTableRequest).pipe(map(x => x.data));
	}

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

	removeOrganisation(organisation) {
		this.facetCriteria.dmpOrganisations.splice(this.facetCriteria.dmpOrganisations.indexOf(organisation), 1);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	// public profileSearch(value: string) {
	// 	return this.datasetProfileService.getDatasetProfiles();
	// }

	public controlModified() {
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	onGrantOptionSelected(item: GrantListingModel) {
		this.facetCriteria.grants.push(item.id);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	onGrantOptionRemoved(item: GrantListingModel) {
		const index = this.facetCriteria.grants.indexOf(item.id);
		if (index >= 0) {
			this.facetCriteria.grants.splice(index, 1);
			this.facetCriteriaChange.emit(this.facetCriteria);
		}
	}

	onDmpOptionSelected(item: DmpListingModel) {
		this.facetCriteria.dmpIds.push(item.id);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	onDmpOptionRemoved(item: DmpListingModel) {
		const index = this.facetCriteria.dmpIds.indexOf(item.id);
		if (index >= 0) {
			this.facetCriteria.dmpIds.splice(index, 1);
			this.facetCriteriaChange.emit(this.facetCriteria);
		}
	}

	onProfileOptionSelected(item: DatasetProfileModel) {
		this.facetCriteria.datasetProfile.push(item.id);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	onProfileOptionRemoved(item: DatasetProfileModel) {
		const index = this.facetCriteria.datasetProfile.indexOf(item.id);
		if (index >= 0) {
			this.facetCriteria.datasetProfile.splice(index, 1);
			this.facetCriteriaChange.emit(this.facetCriteria);
		}
	}

	onOrganizationOptionSelected(item: OrganizationModel) {
		this.facetCriteria.dmpOrganisations.push(item.id);
		this.facetCriteriaChange.emit(this.facetCriteria);
	}

	onOrganizationOptionRemoved(item: OrganizationModel) {
		const index = this.facetCriteria.dmpOrganisations.indexOf(item.id);
		if (index >= 0) {
			this.facetCriteria.dmpOrganisations.splice(index, 1);
			this.facetCriteriaChange.emit(this.facetCriteria);
		}
	}

	filterDmps(value: string): Observable<DataTableData<DmpListingModel>> {
		const fields: Array<string> = new Array<string>();
		fields.push('-finalizedAt');
		const dmpDataTableRequest: DataTableRequest<ExploreDmpCriteriaModel> = new DataTableRequest(0, null, { fields: fields });
		dmpDataTableRequest.criteria = new ExploreDmpCriteriaModel();
		dmpDataTableRequest.criteria.like = value;
		return this.dmpService.getPublicPaged(dmpDataTableRequest, "autocomplete")
	}

	filterTags(value: string): Observable<ExternalSourceItemModel[]> {
		this.filteredTags = undefined;
		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);
		// .subscribe(items => {
		// 	this.filteredTags = items;
		// 	this.filteringTagsAsync = false;
		// });
	}

	filterGrant(query: string) {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const grantRequestItem: DataTableRequest<GrantCriteria> = new DataTableRequest(0, null, { fields: fields });
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		return this.grantService.getPublicPaged(grantRequestItem).pipe(map(x => x.data));
	}

	filterProfile(query: string) {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const profileRequestItem: DataTableRequest<DatasetProfileCriteria> = new DataTableRequest(0, null, { fields: fields });
		profileRequestItem.criteria = new DatasetProfileCriteria();
		profileRequestItem.criteria.like = query;

		return this.datasetProfileService.getDatasetProfiles(profileRequestItem);
		// this.dmpService.getPublicPaged(profileRequestItem, "listing").pipe(map(x => x.data));
	}

	filterOrganisation(value: string) {
		this.filteringOrganisationsAsync = true;
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const dataTableRequest: DataTableRequest<OrganisationCriteria> = new DataTableRequest(0, null, { fields: fields });
		dataTableRequest.criteria = new OrganisationCriteria();
		dataTableRequest.criteria.labelLike = value;

		return this.organisationService.searchPublicOrganisations(dataTableRequest).pipe(map(x => x.data));
	}

	public isAuthenticated(): boolean {
		return !(!this.authentication.current());
	}
}
