import {Component, Input} from "@angular/core";
import {AngularEditorConfig} from "@kolkov/angular-editor";
import {FormControl} from "@angular/forms";

@Component({
	selector: 'rich-text-editor-component',
	template: `
		<div class="editor-wrapper" [class]="wrapperClasses" [formGroup]="parentFormGroup">
			<angular-editor class="full-width editor" [ngClass]="editable ? '': 'disabled'" [id]="id"
							[config]="editorConfig" [formControlName]="controlName"
							placeholder="{{(placeholder? (placeholder | translate) : '') + (required ? ' *': '')}}"
							(paste)="pasteWithoutFormatting($event)"></angular-editor>
			<mat-icon *ngIf="formInput.value" (click)="formInput.patchValue('')" class="clear">close</mat-icon>
		</div>
	`,
	styleUrls: ['./rich-text-editor.component.scss']
})
export class RichTextEditorComponent {
	@Input() parentFormGroup;
	@Input() controlName;
	@Input() id: string = "editor1";
	@Input() placeholder: string = "Enter text";
	@Input() required: boolean = false;
	@Input() wrapperClasses: string = "";
	@Input() editable: boolean = true;

	editorConfig: AngularEditorConfig = {
		editable: this.editable,
		spellcheck: true,
		height: 'auto',
		minHeight: '0',
		maxHeight: 'auto',
		width: '100%',
		minWidth: '0',
		translate: 'yes',
		enableToolbar: true,
		showToolbar: true,
		placeholder: '',
		defaultParagraphSeparator: '',
		defaultFontName: '',
		defaultFontSize: '',
		sanitize: true,
		toolbarPosition: 'top',
		customClasses: [
			{	name: 'H1 header', class: '', tag: 'h1'	},
			{	name: 'H2 header', class: '', tag: 'h2'	},
			{	name: 'H3 header', class: '', tag: 'h3'	},
			{	name: 'H4 header', class: '', tag: 'h4'	},
			{	name: 'H5 header', class: '', tag: 'h5'},
			{	name: 'H6 header', class: '', tag: 'h6'}
		],
		toolbarHiddenButtons: [
			[
				'heading',
				'fontName'
			],
			[
				'fontSize',
				'backgroundColor',
				// 'customClasses',
				'insertImage',
				'insertVideo',
				// 'removeFormat',
				'toggleEditorMode'
			]
		]
	};

	get formInput(): FormControl {
		return this.parentFormGroup.get(this.controlName);
	}

	ngAfterContentInit() {
		this.editorConfig.editable = this.editable;
	}

	pasteWithoutFormatting($event) {
		$event.preventDefault();
		const text = $event.clipboardData.getData("text/plain");
		window.document.execCommand("insertText", false, text);
	}
}
