
import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { Component, Inject, OnInit, ViewChild } 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';
import { Role } from '@app/core/common/enum/role';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { SnackBarNotificationLevel } from '@common/modules/notification/ui-notification-service';
import { TranslateService } from '@ngx-translate/core';

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

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

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

	constructor(
		public invitationService: DmpInvitationService,
		public enumUtils: EnumUtils,
		public route: ActivatedRoute,
		public router: Router,
		private language: TranslateService,
		public dialogRef: MatDialogRef<DmpInvitationDialogComponent>,
		private uiNotificationService: UiNotificationService,
		@Inject(MAT_DIALOG_DATA) public data: any
	) {
		super();
	 }

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

	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) => typeof(item) === 'string' ? item : item.name,
		titleFn: (item) => typeof(item) === 'string' ? item : item.name,
		subtitleFn: (item) => item.email,
		valueAssign: (item) => {
			const result = typeof(item) === 'string' ? item : item.email;
			return result;
		},
		autoSelectFirstOptionOnBlur: true,
		appendClassToItem: [{class: 'invalid-email', applyFunc: (item)=> {
			const val = typeof(item) === 'string'? item : item.email;
			const regexp = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
			return !regexp.test(val);
		}
		}]
	};

	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);
		}
	}

	send(value: any) {
		let invitationObject: any = {};
		invitationObject.dataManagementPlan = this.data.dmpId;
		invitationObject.role = this.formGroup.get('role').value;
		invitationObject.users = [];
		invitationObject.users.push(...(<any[]>this.formGroup.get('users').value).filter(user => typeof(user) === 'string').map(email => ({ email: email, name: email })));
		invitationObject.users.push(...(<any[]>this.formGroup.get('users').value).filter(user => typeof(user) !== 'string'));
		//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(
				complete => {
					this.dialogRef.close();
					this.onCallbackSuccess();
				},
				error => this.onCallbackError(error)
			);
	}

	closeDialog(): void {
		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;
		// });
	}

	hasValue(): boolean {
		return this.formGroup.get('users') && this.formGroup.get('users').value && this.formGroup.get('users').value.length > 0;
	}

	onCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.INVITATION-DIALOG.SUCCESS' ), SnackBarNotificationLevel.Success);
	}

	onCallbackError(errorResponse: any) {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.INVITATION-DIALOG.ERROR' ), SnackBarNotificationLevel.Error);
	}

}
