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

import {map, catchError, switchMap, startWith, takeUntil} 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';
import { BaseComponent } from '@common/base/base.component';
import * as FileSaver from 'file-saver';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';
import { MatTableDataSource } from '@angular/material/table';

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 extends BaseComponent 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[] = ['avatar', 'name', 'email', 'lastloggedin', 'roles'];

	constructor(
		private userService: UserService,
		private languageService: TranslateService,
		public snackBar: MatSnackBar,
		private httpClient: HttpClient,
		private matomoService: MatomoService
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('Admin: Users');
		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;
	}

	// Export user mails
	exportUsers(){
		this.userService.downloadCSV()
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/csv' });
				const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
				FileSaver.saveAs(blob, filename);
			});
	}

	getFilenameFromContentDispositionHeader(header: string): string {
		const regex: RegExp = new RegExp(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/g);

		const matches = header.match(regex);
		let filename: string;
		for (let i = 0; i < matches.length; i++) {
			const match = matches[i];
			if (match.includes('filename="')) {
				filename = match.substring(10, match.length - 1);
				break;
			} else if (match.includes('filename=')) {
				filename = match.substring(9);
				break;
			}
		}
		return filename;
	}

	public setDefaultAvatar(ev: Event) {
		(ev.target as HTMLImageElement).src = 'assets/images/profile-placeholder.png';
	}

	// public principalHasAvatar(): boolean {
	// 	return this.authentication.current().avatarUrl != null && this.authentication.current().avatarUrl.length > 0;
	// }

	// public getPrincipalAvatar(): string {
	// 	return this.authentication.current().avatarUrl;
	// }
}
