import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormArray, FormControl } from '@angular/forms';
import { ExternalSourceUrlModel } from '@app/core/model/external-sources/external-source-url';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';

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

	@Input() public placeholder: string;
	@Input() public autoCompleteConfiguration: SingleAutoCompleteConfiguration;
	@Input() formArray: FormArray;
	@Input() parentTemplate;
	@Input() public options: Array<ExternalSourceUrlModel>;
	@Output() public onItemChange = new EventEmitter<any>();

	public choice: string;
	public formControl = new FormControl();

	constructor() { super(); }
	ngOnInit() {
		this.formControl.disable();
		this.formControl.updateValueAndValidity();

		this.formControl.valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				if (x) {
					this.onItemChange.emit(x);
					this.formControl.reset();
				}
			});
	}

	selectionChange(event) {
		if (this.formControl.disabled) { this.formControl.enable(); this.formControl.updateValueAndValidity(); }
		this.autoCompleteConfiguration.extraData = event.value;
	}

	deleteItem(name: number) {
		this.formArray.removeAt(name);
	}
}

