
import {of as observableOf, merge as observableMerge,  Observable } from 'rxjs';

import {map, catchError, switchMap, startWith} from 'rxjs/operators';
import { DataSource } from '@angular/cdk/table';
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort } from '@angular/material/sort';
import { TranslateService } from '@ngx-translate/core';
import { UserListingModel } from '../../../../core/model/user/user-listing';
import { UserCriteria } from '../../../../core/query/user/user-criteria';
import { UserService } from '../../../../core/services/user/user.service';
import { SnackBarNotificationComponent } from '../../../../library/notification/snack-bar/snack-bar-notification.component';
import { DataTableRequest } from '../../../../core/model/data-table/data-table-request';
import { UserCriteriaComponent } from './criteria/user-criteria.component';
import { BreadcrumbItem } from '../../../misc/breadcrumb/definition/breadcrumb-item';

export class UsersDataSource extends DataSource<UserListingModel> {

	totalCount = 0;

	constructor(
		private _service: UserService,
		private _paginator: MatPaginator,
		private _sort: MatSort,
		private _languageService: TranslateService,
		private _snackBar: MatSnackBar,
		private _criteria: UserCriteriaComponent
	) {
		super();

		//this._paginator.page.pipe(takeUntil(this._destroyed)).subscribe((pageEvent: PageEvent) => {
		//    this.store.dispatch(new LoadPhotosRequestAction(pageEvent.pageIndex, pageEvent.pageSize))
		//})
	}

	connect(): Observable<UserListingModel[]> {
		const displayDataChanges = [
			this._paginator.page
			//this._sort.matSortChange
		];

		// If the user changes the sort order, reset back to the first page.
		//this._sort.matSortChange.pipe(takeUntil(this._destroyed)).subscribe(() => {
		//    this._paginator.pageIndex = 0;
		//})

		return observableMerge(...displayDataChanges).pipe(
			startWith(null),
			switchMap(() => {
				const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
				let fields: Array<string> = new Array();
				if (this._sort.active) { fields = this._sort.direction === 'asc' ? ['+' + this._sort.active] : ['-' + this._sort.active]; }
				const request = new DataTableRequest<UserCriteria>(startIndex, this._paginator.pageSize, { fields: fields });
				request.criteria = this._criteria.getFormData();
				return this._service.getPaged(request);
			}),
			catchError((error: any) => {
				this._snackBar.openFromComponent(SnackBarNotificationComponent, {
					data: { message: 'GENERAL.SNACK-BAR.FORMS-BAD-REQUEST', language: this._languageService },
					duration: 3000,
				});
				this._criteria.onCallbackError(error);
				return observableOf(null);
			}),
			map(result => {
				return result;
			}),
			map(result => {
				if (!result) { return []; }
				if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
				//result.data.forEach((element: any) => {
				//	const roles: String[] = [];
				//	element.roles.forEach((role: any) => {
				//		this._languageService.get(this._utilities.convertFromPrincipalAppRole(role)).pipe(takeUntil(this._destroyed)).subscribe(
				//			value => roles.push(value)
				//		);
				//	});
				//	element.roles = roles;
				//});
				return result.data;
			}),);
	}

	disconnect() {
		// No-op
	}
}

@Component({
	selector: 'app-user-listing-component',
	templateUrl: './user-listing.component.html',
	styleUrls: ['./user-listing.component.scss']
})
export class UserListingComponent implements OnInit, AfterViewInit {

	@ViewChild(MatPaginator, { static: true }) _paginator: MatPaginator;
	@ViewChild(MatSort, { static: true }) sort: MatSort;
	@ViewChild(UserCriteriaComponent, { static: true }) criteria: UserCriteriaComponent;

	breadCrumbs: Observable<BreadcrumbItem[]>;
	dataSource: UsersDataSource | null;
	displayedColumns: String[] = ['name', 'email', 'lastloggedin', 'roles'];

	constructor(
		private userService: UserService,
		private languageService: TranslateService,
		public snackBar: MatSnackBar
	) {

	}

	ngOnInit() {
		this.breadCrumbs = observableOf([{
			parentComponentName: null,
			label: this.languageService.instant('NAV-BAR.USERS-BREADCRUMB'),
			url: "/users"
		}]);
		//this.refresh(); //called on ngAfterViewInit with default criteria
	}

	ngAfterViewInit() {
		setTimeout(() => {
			this.criteria.setRefreshCallback(() => this.refresh());
			this.criteria.setCriteria(this.getDefaultCriteria());
			this.criteria.controlModified();
		});
	}

	refresh() {
		this._paginator.pageSize = 10;
		this._paginator.pageIndex = 0;
		this.dataSource = new UsersDataSource(this.userService, this._paginator, this.sort, this.languageService, this.snackBar, this.criteria);
	}

	getDefaultCriteria(): UserCriteria {
		const defaultCriteria = new UserCriteria();
		return defaultCriteria;
	}
}
