
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatChipInputEvent } from '@angular/material/chips';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { DmpInvitation } from '@app/core/model/dmp/invitation/dmp-invitation';
import { DmpInvitationUser } from '@app/core/model/dmp/invitation/dmp-invitation-user';
import { DmpInvitationUserCriteria } from '@app/core/query/dmp/dmp-invitation-user-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { DmpInvitationService } from '@app/core/services/dmp/dmp-invitation.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-invitation-component',
	templateUrl: 'dmp-invitation.component.html',
})
export class DmpInvitationDialogComponent extends BaseComponent implements OnInit {

	public formGroup: FormGroup;
	public filteredUsersAsync = false;
	public filteredUsers: DmpInvitationUser[];
	public emails: string[] = [];

	visible = true;
	selectable = true;
	removable = true;
	addOnBlur = true;
	readonly separatorKeysCodes: number[] = [ENTER, COMMA];


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

	add(event: MatChipInputEvent): void {
		const input = event.input;
		const value = event.value;
		if ((value || '').trim()) {
			this.emails.push(value.trim());
		}
		if (input) {
			input.value = '';
		}
	}

	remove(email: string): void {
		const index = this.emails.indexOf(email);
		if (index >= 0) {
			this.emails.splice(index, 1);
		}
	}


	constructor(
		public invitationService: DmpInvitationService,
		public route: ActivatedRoute,
		public router: Router,
		public dialogRef: MatDialogRef<DmpInvitationDialogComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { super(); }

	ngOnInit(): void {
		const invitation = new DmpInvitation();
		invitation.dataManagementPlan = this.data.dmpId;
		this.formGroup = invitation.buildForm();
	}


	send(value: any) {
		let invitationObject: any = {};
		invitationObject.dataManagementPlan = this.data.dmpId;
		invitationObject.users = [];

		invitationObject.users.push(...this.formGroup.get('users').value);
		this.emails.forEach(email => {
			invitationObject.users.push({ email: email, name: email });
		});

		this.invitationService.inviteDmpInvitationUsers(invitationObject)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				null, null, () => this.dialogRef.close()
			);
	}

	filterUsers(value: string): Observable<DmpInvitationUser[]> {
		this.filteredUsers = undefined;
		this.filteredUsersAsync = true;
		const request = new RequestItem<DmpInvitationUserCriteria>();
		request.criteria = { like: value };
		return this.invitationService.getDmpInvitationUsers(request)
			.pipe(takeUntil(this._destroyed));
		// .subscribe(items => {
		// 	this.filteredUsers = new JsonSerializer<DmpInvitationUser>(DmpInvitationUser).fromJSONArray(items);
		// 	if (!this.filteredUsers || this.filteredUsers.length === 0) {
		// 		const user = new DmpInvitationUser();
		// 		user.email = value;
		// 		user.name = value;
		// 		this.filteredUsers.push(user);
		// 	}
		// 	this.filteredUsersAsync = false;
		// });
	}
}