import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import { Principal } from '../../../../core/model/auth/principal';
import { UserInfoListingModel } from '../../../../core/model/user/user-info-listing';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { DmpService } from '../../../../core/services/dmp/dmp.service';
import { DmpInvitationDialogComponent } from '../../invitation/dmp-invitation-dialog.component';
import { DmpEditorModel } from '../dmp-editor.model';

@Component({
	selector: 'app-people-tab',
	templateUrl: './people-tab.component.html',
	styleUrls: ['./people-tab.component.scss']
})
export class PeopleTabComponent implements OnInit {

	@Input() formGroup: FormGroup;
	@Input() dmp: DmpEditorModel;
	@Input() isPublic: boolean;
	@Input() isFinalized: boolean;

	constructor(
		private dialog: MatDialog,
		private translate: TranslateService,
		private authentication: AuthService,
		private language: TranslateService,
		private dmpService: DmpService
	) { }

	ngOnInit() {
	}

	openShareDialog(rowId: any, rowName: any) {
		const dialogRef = this.dialog.open(DmpInvitationDialogComponent, {
			// height: '250px',
			// width: '700px',
			autoFocus: false,
			data: {
				dmpId: rowId,
				dmpName: rowName
			}
		});
	}

	roleDisplay(user: UserInfoListingModel) {
		if (user.role === 0) {
			return this.translate.instant('DMP-LISTING.OWNER');
		}
		else if (user.role === 1) {
			return this.translate.instant('DMP-LISTING.MEMBER');
		}
		else {
			return this.translate.instant('DMP-LISTING.OWNER');
		}
	}

	isOwner() {
		const principal: Principal = this.authentication.current();
		var isOwner: boolean = false;
		if (principal) {
			this.formGroup.get('users').value.forEach(element => {
				if (principal.id === element.id && element.role === 0) {
					isOwner = true;
				}
			});
		}
		return isOwner;
	}

	removeCollaborator(id: string) {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '300px',
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-USER'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.REMOVE'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
				isDeleteConfirmation: false
			}
		});
		dialogRef.afterClosed().subscribe(result => {
			if (result) {
				this.formGroup.get('users').setValue(this.formGroup.get('users').value.filter(function (val, index, arr) {
					return val.id !== id;
				}));
			}
		});
	}
}
