import { BaseComponent } from '@common/base/base.component';
import { OnInit, Component, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
import { map, takeUntil } from 'rxjs/operators';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { Observable } from 'rxjs';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { MatDialog } from '@angular/material/dialog';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { LanguageInfo } from '@app/core/model/language-info';
import { LanguageInfoService } from '@app/core/services/culture/language-info-service';
import { RequestItem } from '@app/core/query/request-item';
import { LicenseCriteria } from '@app/core/query/license/license-criteria';
import { AddCostComponent } from '../cost-editor/add-cost/add-cost.component';
import { CostEditorModel } from '../cost-editor/add-cost/add-cost.model';

interface Visible {
	value: boolean;
	name: string;
}

@Component({
	selector: 'license-info',
	templateUrl: './license-info.component.html',
	styleUrls: ['./license-info.component.scss']
})
export class LicenseInfoComponent extends BaseComponent implements OnInit {

	@Input() formGroup: FormGroup = null;
	// @Input() datasetFormGroup: FormGroup;
	@Input() isNewVersion: boolean;
	@Input() isUserOwner: boolean;
	@Input() isClone: boolean;
	@Output() onFormChanged: EventEmitter<any> = new EventEmitter();

	public formControl = new FormControl();

	visibles: Visible[] = [
		{ value: true, name: 'DMP-EDITOR.VISIBILITY.PUBLIC' },
		{ value: false, name: 'DMP-EDITOR.VISIBILITY.RESTRICTED' }
	]

	licenseAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.licenseSearch.bind(this),
		initialItems: (excludedItems: any[]) => this.licenseSearch('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
		displayFn: (item) => item['name'],
		titleFn: (item) => item['name']
	};

	constructor(
		private externalSourcesService: ExternalSourcesService,
		private dialog: MatDialog,
		private languageInfoService: LanguageInfoService
	) {
		super();
	}

	ngOnInit() {

	}

	getLanguageInfos(): LanguageInfo[] {
		return this.languageInfoService.getLanguageInfoValues();
	}

	licenseSearch(query: string): Observable<ExternalSourceItemModel[]> {
		const request = new RequestItem<LicenseCriteria>();
		request.criteria = new LicenseCriteria();
		request.criteria.like = query;
		request.criteria.type = '';
		return this.externalSourcesService.searchLicense(request);
	}

	getAssociates(): any[] {
		let associates: any[] = [];
		//associates = (this.formGroup.get('researchers').value as any[]);
		associates = associates.concat(this.formGroup.get('associatedUsers').value);
		return associates;
	}

	addCost(event: MouseEvent) {
		event.stopPropagation();
		const dialogRef = this.dialog.open(AddCostComponent, {
			data: this.formGroup.get('extraProperties').get('costs')
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				const costsArray = this.formGroup.get('extraProperties').get('costs').value || [];
				costsArray.push(result);
				let costeditModel: CostEditorModel = new CostEditorModel();
				costeditModel = costeditModel.fromModel(result);
				(<FormArray>this.formGroup.get('extraProperties').get('costs')).push(costeditModel.buildForm(null, true));
			}
		});
	}
}
