<template>
  <div class="json-editor">
    <textarea ref="codeMirror"></textarea>
  </div>
</template>

<script>
import CodeMirror from "codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/mode/javascript/javascript.js";
// import "codemirror/addon/lint/lint.css";

import "codemirror/theme/rubyblue.css";

// import "codemirror/addon/lint/lint";
// import "codemirror/addon/lint/json-lint";

export default {
  name: "JSONEditor",

  props: ["value"],

  data() {
    return {
      editor: null,
    };
  },

  watch: {
    value(newValue) {
      console.log("newVlaue", newValue);
      const currentValue = this.editor.getValue();
      if (newValue !== currentValue) {
        this.editor.setValue(JSON.stringify(newValue, null, 2));
      }
    },
  },

  mounted() {
    this.editor = CodeMirror.fromTextArea(this.$refs.codeMirror, {
      lineNumbers: true,
      mode: "application/json",
      gutters: ["CodeMirror-lint-markers"],
      theme: "rubyblue",
      lint: true,
    });

    console.log("value", this.value);
    let jsonObject = this.value;
    if (typeof this.value === "string") {
      jsonObject = JSON.parse(jsonObject);
    }
    this.editor.setValue(JSON.stringify(jsonObject, null, 2));
    this.editor.on("change", (cm) => {
      this.$emit("changed", cm.getValue());
      this.$emit("input", cm.getValue());
    });
  },

  methods: {
    replace(searchValue, replaceValue) {
      const strAllOld = this.editor.getValue();
      const strAllNew = strAllOld.replace(
        new RegExp(searchValue, "g"),
        replaceValue
      );

      if (strAllOld !== strAllNew) {
        this.editor.setValue(strAllNew);
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  width: 100%;
  position: relative;

  ::v-deep.CodeMirror {
    height: 400px;
  }
}
</style>
