
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { GrantType } from '@app/core/common/enum/grant-type';
import { GrantListingModel } from '@app/core/model/grant/grant-listing';
import { GrantFileUploadService } from '@app/core/services/grant/grant-file-upload.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { GrantEditorModel } from '@app/ui/grant/editor/grant-editor.model';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { BaseComponent } from '@common/base/base.component';
import { FormService } from '@common/forms/form-service';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import { environment } from 'environments/environment';
import { Observable, of as observableOf } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';


@Component({
	selector: 'app-grant-editor-component',
	templateUrl: 'grant-editor.component.html',
	styleUrls: ['./grant-editor.component.scss']
})
export class GrantEditorComponent extends BaseComponent implements OnInit, IBreadCrumbComponent {

	breadCrumbs: Observable<BreadcrumbItem[]> = observableOf([]);
	isNew = true;
	grant: GrantEditorModel;
	formGroup: FormGroup = null;
	host: string;
	editMode = false;
	sizeError = false;
	maxFileSize: number = 1048576;
	constructor(
		private grantService: GrantService,
		private route: ActivatedRoute,
		public snackBar: MatSnackBar,
		public router: Router,
		public language: TranslateService,
		private dialog: MatDialog,
		private grantFileUploadService: GrantFileUploadService,
		private uiNotificationService: UiNotificationService,
		private formService: FormService,
		private configurationService: ConfigurationService
	) {
		super();
		this.host = this.configurationService.server;
	}

	ngOnInit() {
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe((params: Params) => {
				const itemId = params['id'];

				if (itemId != null) {
					this.isNew = false;
					this.grantService.getSingle(itemId).pipe(map(data => data as GrantListingModel))
						.pipe(takeUntil(this._destroyed))
						.subscribe(data => {
							this.grant = new GrantEditorModel().fromModel(data);
							this.formGroup = this.grant.buildForm(null, this.grant.type === GrantType.External || !this.editMode);
							const breadCrumbs = [];
							breadCrumbs.push({
								parentComponentName: null,
								label: this.language.instant('NAV-BAR.GRANTS').toUpperCase(),
								url: '/grants'
							});
							breadCrumbs.push({
								parentComponentName: 'GrantListingComponent',
								label: this.grant.label,
								url: '/grants/edit/' + this.grant.id
							});
							this.breadCrumbs = observableOf(breadCrumbs);
						});
				} else {
					this.language.get('QUICKWIZARD.CREATE-ADD.CREATE.QUICKWIZARD_CREATE.ACTIONS.CREATE-NEW-GRANT').pipe(takeUntil(this._destroyed)).subscribe(x => {
						this.breadCrumbs = observableOf([
							{
								parentComponentName: null,
								label: this.language.instant('NAV-BAR.GRANTS').toUpperCase(),
								url: '/grants'
							},
							{
								parentComponentName: 'GrantListingComponent',
								label: x,
								url: '/grants/new/'
							}]
						);
					});

					this.grant = new GrantEditorModel();
					setTimeout(() => {
						this.formGroup = this.grant.buildForm();
					});
				}
			});
	}

	formSubmit(): void {
		this.formService.touchAllFormFields(this.formGroup);
		if (!this.isFormValid()) { return; }
		this.onSubmit();
	}

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

	onSubmit(): void {
		this.grantService.createGrant(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				complete => this.onCallbackSuccess(),
				error => this.onCallbackError(error)
			);
	}

	onCallbackSuccess(): void {
		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(['/grants']);
	}

	onCallbackError(errorResponse: any) {
		this.setErrorModel(errorResponse.error.payload);
		this.formService.validateAllFormFields(this.formGroup);
	}

	public setErrorModel(validationErrorModel: ValidationErrorModel) {
		Object.keys(validationErrorModel).forEach(item => {
			(<any>this.grant.validationErrorModel)[item] = (<any>validationErrorModel)[item];
		});
	}

	public cancel(): void {
		this.router.navigate(['/grants']);
	}

	public delete(): void {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '300px',
			restoreFocus: false,
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
				isDeleteConfirmation: true
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				this.grantService.delete(this.grant.id)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						complete => { this.onCallbackSuccess() },
						error => this.onCallbackError(error)
					);
			}
		});
	}

	public enableForm() {
		if (!this.isExternalGrant()) {
			this.editMode = true;
			this.formGroup.enable();
		}
	}

	public disableForm() {
		this.editMode = false;
		this.formGroup.disable();
	}

	public imgEnable(): boolean {
		if (this.isNew || this.editMode) {
			return true;
		}
		return false;
	}

	public goToGrantDmps() {
		this.router.navigate(['plans/grant/' + this.grant.id], { queryParams: { grantLabel: this.grant.label } });
	}

	public isExternalGrant() {
		return this.grant.type === GrantType.External;
	}

	public previewImage(event): void {
		const fileList: FileList | File = event.target.files;
		const size: number = event.target.files[0].size;  // Get file size.
		this.sizeError = size > this.maxFileSize;  // Checks if file size is valid.
		const formdata: FormData = new FormData();
		if (!this.sizeError) {
			if (fileList instanceof FileList) {
				for (let i = 0; i < fileList.length; i++) {
					formdata.append('file', fileList[i]);
				}
			} else {
				formdata.append('file', fileList);
			}
			this.grantFileUploadService.uploadFile(formdata)
				.pipe(takeUntil(this._destroyed))
				.subscribe(files => this.formGroup.get('files').patchValue(files));
		}
	}
}
