import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FunderModel } from '@app/core/model/funder/funder';
import { TranslateService } from '@ngx-translate/core';
import { FunderCriteria } from '../../../core/query/funder/funder-criteria';
import { RequestItem } from '../../../core/query/request-item';
import { FunderService } from '../../../core/services/funder/funder.service';
import { SingleAutoCompleteConfiguration } from '../../../library/auto-complete/single/single-auto-complete-configuration';
import { FunderFormModel } from '../../dmp/editor/grant-tab/funder-form-model';

@Component({
	selector: 'app-quick-wizard-funder-editor-component',
	templateUrl: './funder-editor-wizard.component.html',
	styleUrls: ['./funder-editor-wizard.component.scss']
})
export class FunderEditorWizardComponent implements OnInit {

	isNew = false;
	funder: FunderFormModel;
	funderLabelCleared = true;
	@Input() funderFormGroup: FormGroup;
	funderAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	constructor(
		private funderService: FunderService,
		private language: TranslateService
	) { }

	ngOnInit() {

		this.funderAutoCompleteConfiguration = {
			filterFn: this.searchFunder.bind(this),
			initialItems: (extraData) => 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'))
		};

		if (!this.funderFormGroup) {
			this.funder = new FunderFormModel();
			this.funderFormGroup = this.funder.buildForm();
		}

		this.funderFormGroup.get('existFunder').enable();
		this.funderFormGroup.get('label').disable();
	}

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

	create() {
		this.isNew = !this.isNew;
		if (this.isNew) {
			this.funderFormGroup.get('existFunder').reset();
			this.funderFormGroup.get('existFunder').disable();
			this.funderFormGroup.get('label').enable();
		} else {
			this.funderFormGroup.get('label').reset();
			this.funderFormGroup.get('label').disable();
			this.funderFormGroup.get('existFunder').enable();
		}
	}
}
