<template>
  <div class="code-editor-component" tabindex="0" @focus="start" :class="focussed? 'focus' : ''">
    <div ref="codeEditor" class="CodeFlask" :class="!value && !focussed? 'empty' : ''">{{this.value}}</div>
    <p v-if="!value && !focussed">(leeg)</p>
  </div>
</template>

<style lang="scss">
  .code-editor-component {
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 0.25rem;
    padding: 0.5rem 0.75rem;
    cursor: text;
    background-color: #f5f5f5;

    p{
      margin-bottom: 0;
      color: #55595c;
    }

    .CodeFlask.empty{
      height: 0;
    }

    // overwrite codeflask css
    .CodeFlask__textarea,
    .CodeFlask__pre,
    code[class*="language-"],
    pre[class*="language-"]{
      padding: 0!important;
    }

    .CodeFlask__pre,
    .CodeFlask__code {
      position: relative;
    }

    &.focus {
      background-color: #fff;
      border-color: #66afe9;

      .CodeFlask__pre,
      .CodeFlask__code {
        position: relative;
      }
    }
  }
</style>

<script>
import 'prismjs/themes/prism.css';
import CodeFlask from 'codeflask';
import 'codeflask/src/codeflask.css';

// This is a base component for different code editors, component can be extended and used as editor for different languages
export default {
  name: 'code-editor',
  docs: `Base component voor verschillende code-editors. Extend en change de codeLanguage om een nieuwe editor een te maken. Default language is HTML`,
  props: {
    value: {
      required: true,
      validator: value => value === null || typeof value === 'string',
      demoValue: '<div>Dit is een demovalue</div>',
    },
  },
  data(){
    return {
      flask: new CodeFlask,
      focussed: false,
      codeLanguage: '',
    };
  },
  mounted(){
    const codeEditor = this.$refs.codeEditor;
    this.flask.run(codeEditor, { language: this.codeLanguage });

    // set eventlisteners on textarea that is initialized by codeflask
    this.flask.onUpdate(this.update);
    this.flask.textarea.addEventListener('blur', this.blur);
    this.flask.textarea.addEventListener('focus', this.focus);
  },
  methods: {
    start() {
      this.$nextTick(() => {
        this.flask.textarea.focus();
      });
    },
    focus() {
      this.focussed = true;
    },
    blur(){
      this.focussed = false;
    },
    update(value){
      this.$emit('input', value);
    },
  },
};
</script>
