<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.file.Tags))
          return
      this.file.Tags = newTags
      this.$emit('markDirty', true)
      this.save()
      },
      updateContent: function (newContent) {
        if (this.$store.state.file.Content === newContent)
          return
        this.$store.state.file.Content = newContent
        this.$emit('markDirty', true)
        this.save()
      },
      save: function () {
        this.$store.state.file.Content = this.content
        console.log("Saving file: " + this.file.Slug)
        this.$store.dispatch('saveFile', this.file)
          .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(err => {
            console.log('err:' + err)
          })
      }
    },
    components: {TagList, Editor}
  }
</script>

<style scoped>

</style>