import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

import * as ace from 'ace-builds';

import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-monokai';
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-beautify';

const THEME = 'ace/theme/monokai';
const LANG = 'ace/mode/json';

@Component({
  selector: 'code-editor',
  templateUrl: './code-editor.component.html',
  styleUrls: ['./code-editor.component.scss']
})
export class CodeEditorComponent implements OnInit {

  private codeEditor: ace.Ace.Editor;
  @ViewChild('codeEditor', {static: true}) private codeEditorElmRef: ElementRef;

  constructor() {
  }

  ngOnInit() {
    ace.require('ace/ext/language_tools');
    const element = this.codeEditorElmRef.nativeElement;
    const editorOptions = CodeEditorComponent.getEditorOptions();
    this.codeEditor = ace.edit(element, editorOptions);
    this.codeEditor.setTheme(THEME);
    this.codeEditor.getSession().setMode(LANG);
    this.codeEditor.setShowFoldWidgets(true);
  }

  // missing property on EditorOptions 'enableBasicAutocompletion' so this is a workaround still using ts
  private static getEditorOptions(): Partial<ace.Ace.EditorOptions> & { enableBasicAutocompletion?: boolean; } {
    const basicEditorOptions: Partial<ace.Ace.EditorOptions> = {
      highlightActiveLine: true,
      minLines: 14,
      maxLines: Infinity,
    };
    const extraEditorOptions = {enableBasicAutocompletion: true};
    return Object.assign(basicEditorOptions, extraEditorOptions);
  }

  /**
   * @returns - the current editor's content.
   */
  public getContent() {
    if (this.codeEditor) {
      return this.codeEditor.getValue();
    }
  }

  public setContent(text) {
    if (this.codeEditor) {
      this.codeEditor.setValue(text);
    }
  }

}
