import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ExternalResearcherService } from '@app/core/services/external-sources/researcher/external-researcher.service';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';
import { CostEditorModel } from './add-cost.model';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { Observable } from 'rxjs';
import { LocalFetchModel } from '@app/core/model/local-fetch/local-fetch.model';
import { CurrencyService } from '@app/core/services/currency/currency.service';

@Component({
	selector: 'app-add-cost-component',
	templateUrl: 'add-cost.component.html',
})
export class AddCostComponent extends BaseComponent implements OnInit {

	public formGroup: FormGroup;

	currencyAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchCurrency.bind(this),
		initialItems: () => this.searchCurrency(''),
		displayFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
		titleFn: (item) => typeof (item) == 'string' ? JSON.parse(item)['name'] : item.name,
		valueAssign: (item) => JSON.stringify(item)
	};

	constructor(
		private externalResearcherService: ExternalResearcherService,
		public dialogRef: MatDialogRef<AddCostComponent>,
		private currencyService: CurrencyService,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { super(); }

	ngOnInit(): void {
		const cost = new CostEditorModel();
		this.formGroup = cost.buildForm();
	}

	send(value: any) {
		this.externalResearcherService.createResearcher(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				null, null, () => this.dialogRef.close()
			);
	}

	addCost() {
		this.dialogRef.close(this.formGroup.value);
	}

	isFormValid() {
		return this.formGroup.valid;
	}

	searchCurrency(like: string): Observable<LocalFetchModel[]> {
		return this.currencyService.get(like);
	}
}
