<template>
  <div
    :style="{ height: myOptions.height + 'px', width: myOptions.width + 'px' }"
  ></div>
</template>

<script>
import { edit } from "ace-builds";

const defaultOptions = {
  value: "",
  width: 500,
  height: 300,
  lang: "javascript",
  theme: "monokai",
  readOnly: false,
  fullScreen: false,
  autoCompletion: false,
  tabSize: 4
};

export default {
  name: "AceEditor",
  props: {
    options: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      myOptions: Object.assign({}, defaultOptions, this.options),
      $ace: null
    };
  },
  watch: {
    options(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.myOptions = Object.assign({}, defaultOptions, newVal);
        this.initAce(this.myOptions);
      }
    }
  },
  methods: {
    setFullScreen() {
      this.$el.classList.toggle("ace-full-screen");
      this.$ace.resize();
    },
    initAce(options) {
      require("ace-builds/webpack-resolver");

      this.$ace = edit(this.$el);
      let session = this.$ace.getSession();
      this.$emit("init", this.$ace);

      session.setMode(`ace/mode/${options.lang}`);
      this.$ace.setTheme(`ace/theme/${options.theme}`);
      this.$ace.setValue(options.value, 1);
      this.$ace.setReadOnly(options.readOnly);
      session.setTabSize(options.tabSize);
      session.setUseSoftTabs(true);

      this.$ace.setShowPrintMargin(false);
      session.setUseWrapMode(true);

      this.$ace.on("change", ($editor, $fn) => {
        const content = this.$ace.getValue();
        this.$emit("input", content, $editor, $fn);
      });
    }
  },
  mounted() {
    if (this.myOptions) {
      this.initAce(this.myOptions);
    } else {
      this.initAce(defaultOptions);
    }
  }
};
</script>
