
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 { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
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 { 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 { 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 { BaseCriteriaComponent } from '@app/ui/misc/criteria/base-criteria.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { TranslateService } from "@ngx-translate/core";
import { Observable, of as observableOf } from 'rxjs';
import { map } from 'rxjs/operators';


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

	@Input() facetCriteria = new ExploreDmpCriteriaModel();
	@Output() facetCriteriaChange = new EventEmitter();
	@Input() displayTitleFunc: (value) => string;
	GrantStateType = GrantStateType;
	grants: Observable<GrantListingModel[]>;
	profiles: Observable<DatasetProfileModel[]>;
	dmpOrganisations: Observable<OrganizationModel[]>;
	grantOptions: Observable<GrantListingModel[]>;
	grantStateOptions: Observable<any[]>;
	filteringOrganisationsAsync = false;
	filteredOrganisations: OrganizationModel[];
	status: GrantStateType;
	IsChecked: boolean;
	IsIndeterminate: boolean;
	LabelAlign: string;
	IsDisabled: boolean;
	Active: string;
	Inactive: string;

	@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'];

	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']
	}

	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']
	}

	constructor(
		public activatedRoute: ActivatedRoute,
		public languageService: TranslateService,
		public grantService: GrantService,
		private authentication: AuthService,
		public datasetProfileService: DatasetService,
		public organisationService: OrganisationService,
		public externalSourcesService: ExternalSourcesService,
		private dmpService: DmpService
	) {
		super(new ValidationErrorModel());
		this.IsChecked = false;
		this.IsIndeterminate = false;
		this.LabelAlign = 'after';
		this.IsDisabled = false;
		this.Active = "0";
		this.Inactive = "1";
	}

	ngOnInit() {
		setTimeout(x => {
			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();
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		this.dmpOrganisations = this.organisationService.searchPublicOrganisations(new DataTableRequest<OrganisationCriteria>(0, null, { fields: fields })).pipe(map(x => x.data));
	}

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

	OnChange($event) {
		// console.log($event);
	}

	OnIndeterminateChange($event) {
		// console.log($event);
	}

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

	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;
		return this.grantService.getPublicPaged(dataTableRequest).pipe(map(x => x.data));
	}

	grantStatusChanged(event) {
		this.facetCriteria.grantStatus = event.value;
		// this.facetCriteria.grantStatus = +event.source.ariaLabel;	// For checkboxes
		// this.facetCriteria.grantStatus = event.option.value.value; // For <app-explore-dmp-filter-item-component>
		// if (!event.source.checked) {
		if (event.value === 'null') {
			this.facetCriteria.grantStatus = null;
			this.grants = observableOf([]);
			this.facetCriteria.grants = [];
		}
		// if (event.checked) {
		// if (event.option.selected) {
		// if (event.source.checked) {
		else {
			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);
	}

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

	onProfileOptionSelected(items: DatasetProfileModel) {
		//this.facetCriteria.datasetProfile.splice(0);
		this.facetCriteria.datasetProfile.push(items.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);
		}
	}

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

	removeProfile(profile) {
		this.facetCriteria.datasetProfile.splice(this.facetCriteria.datasetProfile.indexOf(profile), 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);
		}
	}

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

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

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

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

	dmpOrganisationSearch(value: string): Observable<OrganizationModel[]> {
		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));
	}

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

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

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

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

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

	displayLabel(value) {
		return this.displayTitleFunc ? this.displayTitleFunc(value) : value;
	}

	isOptionSelected(profile: any) {
		return this.formGroup.value.map(x => x.id).indexOf(profile.id) !== -1;
	}

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