
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatStepper } from '@angular/material/stepper';
import { Router } from '@angular/router';
import { DatasetStatus } from '@app/core/common/enum/dataset-status';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { QuickWizardService } from '@app/core/services/quick-wizard/quick-wizard.service';
import { CheckDeactivateBaseComponent } from '@app/library/deactivate/deactivate.component';
import { DatasetCreateWizardModel } from '@app/ui/dataset-create-wizard/dataset-create-wizard.model';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { DatasetEditorWizardComponent } from '@app/ui/quick-wizard/dataset-editor/dataset-editor-wizard.component';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
	selector: 'dataset-create-wizard.component',
	templateUrl: 'dataset-create-wizard.component.html',
	styleUrls: ['./dataset-create-wizard.component.scss'],
})
export class DatasetCreateWizard extends CheckDeactivateBaseComponent implements OnInit, IBreadCrumbComponent {
	breadCrumbs: Observable<BreadcrumbItem[]>;
	@ViewChild(DatasetEditorWizardComponent) datasetEditorWizardComponent: DatasetEditorWizardComponent;
	isLinear = false;
	isNew = true;
	isSubmitted = false;
	formGroup: FormGroup;


	datasetCreateWizardModel: DatasetCreateWizardModel;
	@ViewChild('stepper', { static: true }) stepper: MatStepper;

	constructor(
		private router: Router,
		private formBuilder: FormBuilder,
		public quickWizardService: QuickWizardService,
		public language: TranslateService,
		private uiNotificationService: UiNotificationService,
		private dialog: MatDialog
	) {
		super();
	}

	ngOnInit() {
		this.datasetCreateWizardModel = new DatasetCreateWizardModel();
		this.formGroup = this.datasetCreateWizardModel.buildForm();
		this.language.get('NAV-BAR.DATASET-DESCRIPTION-WIZARD').pipe(takeUntil(this._destroyed)).subscribe(x => {
			this.breadCrumbs = observableOf([
				{
					parentComponentName: 'Dashboard',
					label: x,
					url: '/datasetcreatewizard'
				}]
			);
		})

	}

	save() {
		if (this.formGroup.get('datasets') && this.formGroup.get('datasets').get('datasetsList') && (this.formGroup.get('datasets').get('datasetsList') as FormArray).length > 0) {
			for (let control of (this.formGroup.get('datasets').get('datasetsList') as FormArray).controls) {
				control.get('status').setValue(DatasetStatus.Draft);
			}
			// this.onSubmitSave();
			const dmpId = this.formGroup.get('dmpMeta').get('dmp').value.id;
			this.quickWizardService.createQuickDatasetWizard(this.formGroup.value)
				.pipe(takeUntil(this._destroyed))
				.subscribe(
					complete => this.onCallbackSuccess(dmpId)
				);
		} else {
			return;
		}
	}

	saveFinalize() {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '300px',
			restoreFocus: false,
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.FINALIZE-ITEM'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
				isDeleteConfirmation: false
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				if (!this.isFormValid()) { return; }
				if (this.formGroup.get('datasets') && this.formGroup.get('datasets').get('datasetsList') && (this.formGroup.get('datasets').get('datasetsList') as FormArray).length > 0) {
					for (let control of (this.formGroup.get('datasets').get('datasetsList') as FormArray).controls) {
						control.get('status').setValue(DatasetStatus.Finalized);
					}
					this.onSubmitSaveAndFinalize();
				} else {
					return;
				}
			}
		});
	}

	// onSubmitSave() {
	// 	const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
	// 		data: {
	// 			message: this.language.instant('QUICKWIZARD.SAVE-DIALOG.TITLE'),
	// 			confirmButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.AFFIRMATIVE'),
	// 			cancelButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.NEGATIVE')
	// 		}
	// 	});
	// 	dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
	// 		if (result) {
	// 			this.datasetEditorWizardComponent.addDataset();
	// 		} else if (result === false) {
	// 			this.quickWizardService.createQuickDatasetWizard(this.formGroup.value)
	// 				.pipe(takeUntil(this._destroyed))
	// 				.subscribe(
	// 					complete => this.onCallbackSuccess()
	// 				)
	// 		}
	// 	});
	// }

	onSubmitSaveAndFinalize() {
		const dmpId = this.formGroup.get('dmpMeta').get('dmp').value.id;
		this.quickWizardService.createQuickDatasetWizard(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				complete => this.onCallbackSuccess(dmpId)
			);
	}

	hasDatasets() {
		if ((this.formGroup.get('datasets').get('datasetsList') as FormArray).length > 0) {
			return true;
		} else {
			return false;
		}
	}

	public isFormValid() {
		return this.formGroup.valid;
	}

	onCallbackSuccess(dmpId: string): void {
		this.isSubmitted = true;
		this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/plans/overview/' + dmpId]);
	}

	isActive(step: string): boolean {
		switch (step) {
			case 'step1':
				return this.stepper.selectedIndex == 0;
			case 'step2':
				return this.stepper.selectedIndex == 1;
		}
	}

	canDeactivate(): boolean {
		return this.isSubmitted || !this.formGroup.dirty;
	}
}
