
import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { MatStepper } from '@angular/material/stepper';
import { ActivatedRoute, Router } from '@angular/router';
import { DmpStatus } from '@app/core/common/enum/dmp-status';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { DmpCriteria } from '@app/core/query/dmp/dmp-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { DatasetWizardService } from '@app/core/services/dataset-wizard/dataset-wizard.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { DatePipe } from "@angular/common";
import { TranslateService } from "@ngx-translate/core";

@Component({
	selector: 'dataset-dmp-selector-component',
	templateUrl: 'dataset-dmp-selector.component.html',
	styleUrls: ['./dataset-dmp-selector.component.scss'],
})

export class DatasetDmpSelector extends BaseComponent implements OnInit, IBreadCrumbComponent {

	breadCrumbs: Observable<BreadcrumbItem[]>;
	dmpAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	@Input() formGroup: FormGroup;
	@Input() datasetFormGroup: FormGroup;
	@Input() stepper: MatStepper;
	formControl: FormControl;
	availableProfiles: DatasetProfileModel[] = [];

	constructor(
		public dmpService: DmpService,
		private datasetWizardService: DatasetWizardService,
		private language: TranslateService,
		private datepipe: DatePipe
	) {
		super();
	}

	ngOnInit() {
		this.dmpAutoCompleteConfiguration = {
			filterFn: this.searchDmp.bind(this),
			initialItems: (extraData) => this.searchDmp(''),
			displayFn: (item) => item['label'],
			titleFn: (item) => item['label'],
			subtitleFn: (item) => this.language.instant('QUICKWIZARD.CREATE-ADD.ADD.CREATED') + " " + this.datepipe.transform(item['creationTime'], 'yyyy-MM-dd')
		};

		this.formGroup.get('dmp').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				if (x) { this.loadDatasetProfiles(); }
				else {
					this.availableProfiles = [];
					this.formGroup.get('datasetProfile').reset();
				}
			});

		this.formGroup.get('datasetProfile').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				(this.datasetFormGroup.get('datasetsList') as FormArray).controls.length = 0;
			});
	}

	searchDmp(query: string): Observable<DmpListingModel[]> {
		const fields: Array<string> = new Array<string>();
		fields.push('-created');
		const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, null, { fields: fields });
		dmpDataTableRequest.criteria = new DmpCriteria();
		dmpDataTableRequest.criteria.status = DmpStatus.Draft;
		dmpDataTableRequest.criteria.like = query;

		return this.dmpService.getPaged(dmpDataTableRequest, "autocomplete").pipe(
			map(y => y.data));
	}

	loadDatasetProfiles() {
		const datasetProfileRequestItem: RequestItem<DatasetProfileCriteria> = new RequestItem();
		datasetProfileRequestItem.criteria = new DatasetProfileCriteria();
		datasetProfileRequestItem.criteria.id = this.formGroup.get('dmp').value.id;
		if (datasetProfileRequestItem.criteria.id) {
			this.datasetWizardService.getAvailableProfiles(datasetProfileRequestItem)
				.pipe(takeUntil(this._destroyed))
				.subscribe(items => {
					this.availableProfiles = items;
					if (this.availableProfiles.length === 1) {
						this.formGroup.get('datasetProfile').patchValue(this.availableProfiles[0]);
						this.stepper.next();
					}
				});
		}
	}

	datasetChanged($event) {
		this.stepper.next();
	}
}
