import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { DmpUploadDialogue } from '../listing/upload-dialogue/dmp-upload-dialogue.component';
import { UiNotificationService, SnackBarNotificationLevel } from '@app/core/services/notification/ui-notification-service';
import { TranslateService } from '@ngx-translate/core';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { takeUntil } from 'rxjs/operators';
import { BaseComponent } from '@common/base/base.component';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
	selector: 'app-start-new-dmp',
	templateUrl: './start-new-dmp-dialog.component.html',
	styleUrls: ['./start-new-dmp-dialog.component.scss']
})
export class StartNewDmpDialogComponent extends BaseComponent {

	public isDialog: boolean = false;

	constructor(
		public dialogRef: MatDialogRef<StartNewDmpDialogComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any,
		private router: Router,
		public dialog: MatDialog,
		private uiNotificationService: UiNotificationService,
		private language: TranslateService,
		private dmpService: DmpService,
		private httpClient: HttpClient,
		private matomoService: MatomoService
	) {
		super();
		this.isDialog = data.isDialog;
	}

	ngOnInit() {
		this.matomoService.trackPageView('Start New DMP Dialog');
	}

	cancel() {
		this.dialogRef.close();
	}

	send() {
		this.dialogRef.close(this.data);
	}

	close() {
		this.dialogRef.close(false);
	}

	startWizard() {
		this.router.navigate(['/plans/new']);
		this.close();
	}

	uploadFile(event) {
		const dialogRef = this.dialog.open(DmpUploadDialogue, {
			width: '528px',
			data: {
				fileList: FileList,
				success: Boolean,
				dmpTitle: String
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result && result.success) {
				this.dmpService.uploadXml(result.fileList[0], result.dmpTitle, result.dmpProfiles)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						(complete) => {
							this.onCallbackImportComplete();
							this.dialog.closeAll();
						},
						(error) => this.onCallbackImportFail(error.error)
					);
			}
		});
	}

	private onCallbackImportComplete() {
		this.uiNotificationService.snackBarNotification(this.language.instant('DMP-UPLOAD.UPLOAD-SUCCESS'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/reload']).then(() => this.router.navigate(['/plans']));
		// this.router.navigate(['/reload']).then(() => this.isPublic ? this.router.navigate(['/explore-plans']) : this.router.navigate(['/plans']));
	}

	private onCallbackImportFail(error: any) {
		this.uiNotificationService.snackBarNotification(this.language.instant(error.message), SnackBarNotificationLevel.Error);
	}

}
