import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { BaseComponent } from '@common/base/base.component';
import { UserGuideService } from '@app/core/services/user-guide/user-guide.service';
import { takeUntil } from 'rxjs/operators';
import { UiNotificationService, SnackBarNotificationLevel } from '@app/core/services/notification/ui-notification-service';
import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { environment } from 'environments/environment';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
import { AuthService } from '@app/core/services/auth/auth.service';
import { LanguageService } from '@app/core/services/language/language.service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-user-guide-editor',
  templateUrl: './user-guide-editor.component.html',
  styleUrls: ['./user-guide-editor.component.scss']
})
export class UserGuideEditorComponent extends BaseComponent implements OnInit {
	public formGroup: FormGroup;
	private formBuilder: FormBuilder;

  constructor(private userGuideService: UserGuideService,
	private uiNotificationService: UiNotificationService,
	  private translate: TranslateService,
	  private router: Router,
	  private configurationService: ConfigurationService,
	  private languageService: LanguageService,
	  private httpClient: HttpClient,
		private matomoService: MatomoService
	) { super(); }

  ngOnInit() {
	this.matomoService.trackPageView('Admin: User Guide Editor');
	this.formBuilder = new FormBuilder();
	this.formGroup = this.formBuilder.group({
		name: [''],
		html: ['']
	});
	this.userGuideService.getUserGuide(this.languageService.getCurrentLanguage()).pipe(takeUntil(this._destroyed)).subscribe(data => {
		const contentDispositionHeader = data.headers.get('Content-Disposition');
		const filename = contentDispositionHeader.split(';')[1].trim().split('=')[1].replace(/"/g, '');

		this.formGroup.get('name').patchValue(filename);
		this.loadFile(data.body);
	});
  }

  private parseText(source: string): string {
	source = source.replace(/src="images/g, `src="${this.configurationService.guideAssets}`);
	source = source.replace(/\r\n +>/g, '>\n');
	const brokenElements = Array.from(new Set(source.match(/&lt;\/\w+\d* &gt;/g)));
	if (!isNullOrUndefined(brokenElements)) {
		brokenElements.forEach((brokenElement) => {
			const tempvalue = brokenElement.match(/\/\w+\d*/)[0];
			source = source.replace(new RegExp(brokenElement, 'g'), `<${tempvalue}>\n`);
		});
	}
	return source;
  }

  loadFile(data: Blob) {
	const reader = new FileReader();
	reader.addEventListener('load', () => {
		let result = this.parseText(reader.result as string);
		//result = result.replace(/class="href" path="/g, 'href="#');
	 	this.formGroup.get('html').patchValue(result);
  }, false);
	reader.readAsText(data);
  }

  submit() {
	  let result = this.parseText(this.formGroup.get('html').value);
	  //result = result.replace(/href="#/g, 'class="href" path="');
	  this.formGroup.get('html').patchValue(result);
	this.userGuideService.updateUserGuide(this.formGroup.value).pipe(takeUntil(this._destroyed))
	.subscribe(
		complete => {
			 this.onCallbackSuccess(complete);
		},
		error => {
			this.onCallbackError(error);
		}
	);

}

onCallbackSuccess(id?: String): void {
  this.uiNotificationService.snackBarNotification( this.translate.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
  this.router.navigate(['/reload']).then(() => this.router.navigate(['/user-guide-editor']));
}

onCallbackError(error: any) {
  this.uiNotificationService.snackBarNotification( error, SnackBarNotificationLevel.Error);
  //this.validateAllFormFields(this.formGroup);
}

}
