<template>
    <div>
        <b-container fluid>
            <b-row>
                <b-col>
                    <Editor :content="content" @change="updateContent"/>
                </b-col>
            </b-row>
            <b-row>
                <b-col cols="1"><label style="padding-top: 0.5em" for="tagList">Tags</label></b-col>
                <b-col cols="10">
                    <TagList id="tagList" :tags="tags" @change="tagUpdate"/>
                </b-col>
            </b-row>
        </b-container>
    </div>
</template>

<script>
  import Editor from "./Editor"
  import TagList from "./TagList"
  import _ from 'lodash'

  export default {
    name: "MainEditor",
    props: {
      slug: String
    },
    created() {
      if (this.$props.slug) {
        this.getFile(this.$props.slug)
      }
      this.save = _.debounce(this.save, 2000)
    },
    computed: {
      tags: function () {
        if (this.$store.state.file) {
          return this.$store.state.file.Tags
        }
        return []
      },
      content: function () {
        if (this.$store.state.file) {
          return this.$store.state.file.Content
        }
        return "= Main Editor"
      }
    },
    watch: {
      slug: function (newValue) {
        this.getFile(newValue)
      }
    },
    methods: {
      getFile: function (slug) {
        this.$store.dispatch('getFile', slug)
      },
      tagUpdate: function(newTags) {
        if (JSON.stringify(newTags) === JSON.stringify(this.$store.state.file.Tags))
          return
      this.$store.commit('setTags', newTags)
      this.$emit('markDirty', true)
      this.save()
      },
      updateContent: function (newContent) {
        if (this.$store.state.file.Content === newContent)
          return
        this.$store.commit('setContent', newContent)
        this.$emit('markDirty', true)
        this.save()
      },
      save: function () {
        this.$store.commit('setContent', this.content)
        this.$store.dispatch('saveFile')
          .then(res => {
            this.$emit('markDirty', false)
            this.$store.dispatch('updateSearch')
            if (res.data.Slug != this.$route.params.slug)
              this.$router.replace({params: { slug: res.data.Slug }})
          })
          .catch(() => { })
      }
    },
    components: {TagList, Editor}
  }
</script>

<style scoped>

</style>