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

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

	isNew = false;
	project: ProjectFormModel;
	@Input() formGroup: FormGroup;
	projectAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	constructor(
		private projectService: ProjectService,
		private language: TranslateService
	) { }

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

		if (!this.formGroup) {
			this.project = new ProjectFormModel();
			this.formGroup = this.project.buildForm();
		}

		this.formGroup.get('existProject').enable();
		this.formGroup.get('label').disable();
		this.formGroup.get('description').disable();
	}

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

	create() {
		this.isNew = !this.isNew;
		if (this.isNew) {
			this.formGroup.get('existProject').disable();
			this.formGroup.get('existProject').reset();
			this.formGroup.get('label').enable();
			this.formGroup.get('description').enable();
		} else {
			this.formGroup.get('existProject').enable();
			this.formGroup.get('label').disable();
			this.formGroup.get('label').reset();
			this.formGroup.get('description').disable();
			this.formGroup.get('description').reset();
		}
	}

}
