import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FunderCriteria } from '@app/core/query/funder/funder-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { ProjectCriteria } from '@app/core/query/project/project-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { FunderService } from '@app/core/services/funder/funder.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { ProjectService } from '@app/core/services/project/project.service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { GrantTabModel } from '@app/ui/dmp/editor/grant-tab/grant-tab-model';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';

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

	@Input() grantformGroup: FormGroup;
	@Input() projectFormGroup: FormGroup;
	@Input() funderFormGroup: FormGroup = null;
	@Input() isFinalized: boolean;
	@Input() isNewVersion: boolean;
	@Input() isNew: boolean;
	@Input() isUserOwner: boolean;
	@Input() isClone: boolean = false;

	isCreateNew = false;
	isCreateNewProject = false;
	isCreateNewFunder = false;
	grant: GrantTabModel;

	grantAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	projectAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	funderAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	constructor(
		private grantService: GrantService,
		private projectService: ProjectService,
		private funderService: FunderService,
		private language: TranslateService
	) {
		super();
	}

	getGrantIdText(item) {
		if (item.reference != null && typeof item.reference == 'string') {
			const parts = (item.reference as String).split('::');
			return parts.length > 1 ? ' (' + parts[parts.length - 1] + ')' : '';
		}
		return '';
	}

	ngOnInit() {

		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();

		this.funderAutoCompleteConfiguration = {
			filterFn: this.searchFunder.bind(this),
			initialItems: () => this.searchFunder(''),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label'],
			subtitleFn: (item) => item['source'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['source'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
		}

		this.grantAutoCompleteConfiguration = {
			filterFn: this.searchGrant.bind(this),
			initialItems: () => this.searchGrant(''),
			displayFn: (item) => item['label'] + this.getGrantIdText(item),
			titleFn: (item) => item['label'] + this.getGrantIdText(item),
			subtitleFn: (item) => item['source'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['source'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
		};

		this.projectAutoCompleteConfiguration = {
			filterFn: this.searchProject.bind(this),
			initialItems: () => this.searchProject(''),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label'],
			subtitleFn: (item) => item['source'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['source'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE'))
		}

		this.isCreateNew = (this.grantformGroup.get('label').value != null && this.grantformGroup.get('label').value.length > 0);
		this.isCreateNewProject = (this.projectFormGroup.get('label').value != null && this.projectFormGroup.get('label').value.length > 0);
		this.isCreateNewFunder = (this.funderFormGroup.get('label').value != null && this.funderFormGroup.get('label').value.length > 0);
		this.setGrantValidators();
		this.setProjectValidators();
		this.setFunderValidators();
		this.registerFormListeners();
		if (this.isNew && !this.isClone) {
			this.grantformGroup.reset();
			this.grantformGroup.disable();
		}
	}

	searchGrant(query: any) {
		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		if (this.funderFormGroup.get('existFunder').value) {
			grantRequestItem.criteria.funderReference = this.funderFormGroup.controls['existFunder'].value.reference;
		}
		return this.grantService.getWithExternal(grantRequestItem);
	}

	searchProject(query: string) {
		const projectRequestItem: RequestItem<ProjectCriteria> = new RequestItem();
		projectRequestItem.criteria = new ProjectCriteria();
		projectRequestItem.criteria.like = query;
		return this.projectService.getWithExternal(projectRequestItem);
	}

	searchFunder(query: string) {
		const funderRequestItem: RequestItem<FunderCriteria> = new RequestItem();
		funderRequestItem.criteria = new FunderCriteria();
		funderRequestItem.criteria.like = query;
		return this.funderService.getWithExternal(funderRequestItem)
	}

	createGrant() {
		if (this.isNewVersion) { return };
		if (this.isGrantDisabled()) return;
		this.isCreateNew = !this.isCreateNew;
		this.setGrantValidators();
	}

	createProject() {
		if (this.isNewVersion) { return };
		this.isCreateNewProject = !this.isCreateNewProject;
		this.setProjectValidators();
	}

	createFunder() {
		if (this.isNewVersion) { return };
		this.isCreateNewFunder = !this.isCreateNewFunder;
		this.setFunderValidators();
	}

	setGrantValidators() {
		if (this.isCreateNew) {
			this.grantformGroup.get('existGrant').disable();
			this.grantformGroup.get('label').enable();
			this.grantformGroup.get('description').enable();
		} else if (this.isClone && !this.isNewVersion) {
			this.grantformGroup.get('existGrant').enable();
			this.grantformGroup.get('label').disable();
			this.grantformGroup.get('label').reset();
			this.grantformGroup.get('description').disable();
			this.grantformGroup.get('description').reset();
		} else if (this.isFinalized || this.isNewVersion || !this.isUserOwner) {
			this.grantformGroup.get('existGrant').disable();
			this.grantformGroup.get('label').disable();
			this.grantformGroup.get('description').disable();
		} else {
			this.grantformGroup.get('existGrant').enable();
			this.grantformGroup.get('label').disable();
			this.grantformGroup.get('label').reset();
			this.grantformGroup.get('description').disable();
			this.grantformGroup.get('description').reset();
		}
	}

	setProjectValidators() {
		if (this.isCreateNewProject) {
			this.projectFormGroup.get('existProject').disable();
			this.projectFormGroup.get('label').enable();
			this.projectFormGroup.get('description').enable();
		} else if (this.isClone && !this.isNewVersion) {
			this.projectFormGroup.get('existProject').enable();
			this.projectFormGroup.get('label').disable()
			this.projectFormGroup.get('label').reset();
			this.projectFormGroup.get('description').disable();
			this.projectFormGroup.get('description').reset();
		} else if (this.isFinalized || this.isNewVersion || !this.isUserOwner) {
			this.projectFormGroup.get('existProject').disable();
			this.projectFormGroup.get('label').disable();
			this.projectFormGroup.get('description').disable();
		} else {
			this.projectFormGroup.get('existProject').enable();
			this.projectFormGroup.get('label').disable();
			this.projectFormGroup.get('label').reset();
			this.projectFormGroup.get('description').disable();
			this.projectFormGroup.get('description').reset();
		}
	}

	setFunderValidators() {
		if (this.isCreateNewFunder) {
			this.funderFormGroup.get('existFunder').disable();
			this.funderFormGroup.get('label').enable();
		} else if (this.isClone && !this.isNewVersion) {
			if (this.funderFormGroup.get('existFunder')) {
				this.funderFormGroup.get('existFunder').enable();
				this.funderFormGroup.get('label').disable();
				this.funderFormGroup.get('label').reset();
			} else {
				this.funderFormGroup.get('label').enable();
			}
		} else if (this.isFinalized || this.isNewVersion || !this.isUserOwner) {
			this.funderFormGroup.get('existFunder').disable();
			this.funderFormGroup.get('label').disable();
		} else {
			this.funderFormGroup.enable();
			this.funderFormGroup.get('label').disable();
			this.funderFormGroup.get('label').reset();
		}
	}

	registerFormListeners() {
		this.funderFormGroup.valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.funderValueChanged(x);
			})
	}

	funderValueChanged(funder: any) {
		if ((funder.label !== "" && funder.label != null && funder.label !== undefined)
			|| (funder.existFunder !== null && funder.existFunder !== undefined && funder.existFunder.id !== undefined)) {
			this.grantformGroup.reset();
			this.grantformGroup.enable();
			this.setGrantValidators();
		} else {
			this.grantformGroup.reset();
			this.grantformGroup.disable();
			if (this.isCreateNew) this.isCreateNew = !this.isCreateNew;
		}
	}

	isGrantDisabled() {
		return this.grantformGroup.disabled;
	}

	showToggleButton() {
		return (!this.isFinalized && this.isUserOwner) || this.isClone;
	}
}
