import { createVNode as _createVNode } from "vue";
import { computed, defineComponent, onMounted, ref, toRef, watch } from "vue";
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
const prefixCls = 'x-code';
const Code = defineComponent({
  name: prefixCls,
  props: {
    code: String,
    language: String,
    trim: {
      default: true
    }
  },

  setup(props, {
    slots
  }) {
    const codeRef = ref();
    const resultRef = computed(() => {
      let code = props.code;
      if (!code) return {};
      if (props.trim) code = code.trim();

      if (props.language) {
        return hljs.highlight(code, {
          language: props.language,
          ignoreIllegals: true
        });
      } else {
        return hljs.highlightAuto(code);
      }
    });
    const languageRef = computed(() => resultRef.value.language || props.language);

    function setCode() {
      if (slots.default) return;
      if (!codeRef.value) return;
      codeRef.value.innerHTML = resultRef.value.value;
    }

    onMounted(setCode);
    watch([toRef(props, 'code'), toRef(props, 'language')], setCode);
    return () => {
      var _slots$default;

      const cls = [prefixCls];
      const language = languageRef.value;
      return _createVNode("code", {
        "class": ['hljs ' + language, cls]
      }, [slots.default ? (_slots$default = slots.default) === null || _slots$default === void 0 ? void 0 : _slots$default.call(slots) : _createVNode("pre", {
        "ref": codeRef
      }, null)]);
    };
  }

});

Code.install = app => {
  app.component(Code.name, Code);
};

export default Code;