import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';

@Component({
	styleUrls: ['available-profiles.component.scss'],
	selector: 'app-available-profiles-component',
	templateUrl: 'available-profiles.component.html',
})
export class AvailableProfilesComponent extends BaseComponent implements OnInit {

	public formGroup: FormGroup;
	public profiles: DatasetProfileModel[] = [];
	public selectedProfiles: DatasetProfileModel[] = [];
	public selectedOptions: any;
	constructor(
		private datasetService: DatasetService,
		private dialogRef: MatDialogRef<AvailableProfilesComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { super(); }

	ngOnInit(): void {
		this.formGroup = this.data['profiles'];
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const profileRequestItem: DataTableRequest<DatasetProfileCriteria> = new DataTableRequest(0, null, { fields: fields });
		profileRequestItem.criteria = new DatasetProfileCriteria();
		profileRequestItem.criteria.like = '';

		this.datasetService.getDatasetProfiles(profileRequestItem)
			.pipe(takeUntil(this._destroyed))
			.subscribe(data => {
				
				const dataArray  = data;
				dataArray.sort((a,b)=> (a.label as string).localeCompare(b.label));
				this.profiles = dataArray;
			});
	}

	addProfiles(profiles) {
		profiles.selectedOptions.selected.forEach(element => {
			const selectedElement = {
				id: element.value.id,
				label: element.value.label,
				description: element.value.description
			}
			this.selectedProfiles.push(selectedElement);
		});
		this.formGroup.setValue(this.selectedProfiles);
		this.dialogRef.close();
	}

	isOptionSelected(profile: any) {
		return this.formGroup.value ? this.formGroup.value.map(x => x.id).indexOf(profile.id) !== -1 : null;
	}
}
