
import { DataSource } from '@angular/cdk/table';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DmpProfileListing } from '@app/core/model/dmp-profile/dmp-profile-listing';
import { DmpProfileCriteria } from '@app/core/query/dmp/dmp-profile-criteria';
import { DmpProfileService } from '@app/core/services/dmp/dmp-profile.service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { DmpProfileCriteriaComponent } from '@app/ui/admin/dmp-profile/listing/criteria/dmp-profile-criteria.component';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { BaseComponent } from '@common/base/base.component';
import { SnackBarNotificationLevel } from '@common/modules/notification/ui-notification-service';
import { TranslateService } from '@ngx-translate/core';
import { merge as observableMerge, Observable, of as observableOf } from 'rxjs';
import { map, startWith, switchMap, takeUntil } from 'rxjs/operators';
import { DialodConfirmationUploadDmpProfiles } from './criteria/dialog-confirmation-upload-profile/dialog-confirmation-upload-profiles.component';


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

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

	dataSource: DatasetDataSource | null;
	displayedColumns: String[] = ['label', 'status', 'created'];
	pageEvent: PageEvent;
	titlePrefix: String;
	dmpId: String;
	breadCrumbs: Observable<BreadcrumbItem[]>;

	statuses = [
		{ value: '0', viewValue: 'DMP-PROFILE-LISTING.STATUS.DRAFT' },// active
		{ value: '1', viewValue: 'DMP-PROFILE-LISTING.STATUS.FINALIZED' }// inactive
	];

	constructor(
		private router: Router,
		private languageService: TranslateService,
		public snackBar: MatSnackBar,
		public route: ActivatedRoute,
		public dmpProfileService: DmpProfileService,
		private httpClient: HttpClient,
		private matomoService: MatomoService,
		private dialog: MatDialog,
		private uiNotificationService: UiNotificationService,
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('Admin: DMP Templates');
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe((params: Params) => {
				this.dmpId = params['dmpId'];
				this.criteria.setCriteria(this.getDefaultCriteria());
				this.refresh();
				this.criteria.setRefreshCallback(() => this.refresh());
				this.breadCrumbs = observableOf([{
					parentComponentName: null,
					label: this.languageService.instant('NAV-BAR.DMP-TEMPLATES'),
					url: '/dmp-profiles'
				}]);
			});
	}

	refresh() {
		this.dataSource = new DatasetDataSource(this.dmpProfileService, this._paginator, this.sort, this.criteria);
	}

	rowClick(rowId: String) {
		this.router.navigate(['dmp-profiles/' + rowId]);
	}

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

	// makeItPublic(id: String) {
	//   debugger;
	//   this.datasetService.makeDatasetPublic(id).pipe(takeUntil(this._destroyed)).subscribe();
	// }

	parseStatus(value: number): string{
		const stringVal = value.toString()
		try{
			return this.statuses.find(status => status.value === stringVal).viewValue;
		}catch{
			return stringVal;
		}
	}

	openDialog(): void {
		const dialogRef = this.dialog.open(DialodConfirmationUploadDmpProfiles, {
			restoreFocus: false,
			data: {
				message: this.languageService.instant('DMP-PROFILE-LISTING.UPLOAD.UPLOAD-XML-FILE-TITLE'),
				confirmButton: this.languageService.instant('DMP-PROFILE-LISTING.UPLOAD.UPLOAD-XML'),
				cancelButton: this.languageService.instant('DMP-PROFILE-LISTING.UPLOAD.UPLOAD-XML-FILE-CANCEL'),
				name: '',
				file: FileList,
				sucsess: false
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(data => {
			if (data && data.sucsess && data.name != null && data.file != null) {
				this.dmpProfileService.uploadFile(data.file, data.name)
					.pipe(takeUntil(this._destroyed))
					.subscribe(_=>{
						this.uiNotificationService.snackBarNotification(this.languageService.instant('DMP-PROFILE-LISTING.MESSAGES.TEMPLATE-UPLOAD-SUCCESS'), SnackBarNotificationLevel.Success);
						this.refresh();
					},
					error=>{
						this.uiNotificationService.snackBarNotification(error.message, SnackBarNotificationLevel.Error);
					});
			}
		});
	}
	getStatusClass(status: number):string{
		
		if(status === 1){//finalized
			return 'status-chip-finalized'
		}
		if(status === 0){
			return 'status-chip-draft';
		}
		return '';
	}
}

export class DatasetDataSource extends DataSource<DmpProfileListing> {

	totalCount = 0;

	constructor(
		private _service: DmpProfileService,
		private _paginator: MatPaginator,
		private _sort: MatSort,
		private _criteria: DmpProfileCriteriaComponent
	) {
		super();

	}

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

		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<DmpProfileCriteria>(startIndex, this._paginator.pageSize, { fields: fields });
				request.criteria = this._criteria.criteria;
				return this._service.getPaged(request);
			}),
			/*.catch((error: any) => {
              this._snackBar.openFromComponent(SnackBarNotificationComponent, {
                data: { message: 'GENERAL.SNACK-BAR.FORMS-BAD-REQUEST', language: this._languageService },
                duration: 3000,
                extraClasses: ['snackbar-warning']
              });
              //this._criteria.criteria.onCallbackError(error);
              return Observable.of(null);
            })*/
			map(result => {
				return result;
			}),
			map(result => {
				if (!result) { return []; }
				if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
				return result.data;
			}));
	}

	disconnect() {
		// No-op
	}
}
