import { Component, OnInit, Input } from '@angular/core';
import { BaseComponent } from '@common/base/base.component';
import { FormArray, FormControl } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
import { CostModel } from '@app/core/model/dmp/cost';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { CurrencyService } from '@app/core/services/currency/currency.service';
import { Observable } from 'rxjs';
import { LocalFetchModel } from '@app/core/model/local-fetch/local-fetch.model';
import { CostEditorModel } from '../add-cost/add-cost.model';

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

	@Input() form: FormArray;

	private cost: CostEditorModel[] = [];

	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 currencyService: CurrencyService,
  ) {
	  super();
  }

  ngOnInit() {
  }

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

switchEditMode(event: number) {
	const control = this.form.at(event);
	if (control.disabled) {
		this.cost[event] = control.value;
		control.enable();
	} else {
		control.disable();
	}
}

removeCost(event: number) {
	this.form.removeAt(event);
}

revertEdits(event: number) {
	this.form.at(event).setValue(this.cost[event]);
	this.form.at(event).disable();
}

}
