import Vue from 'vue'

function separateBlogs(blogs) {
  const published = []
  const drafts = []

  blogs.forEach(blog => {
    blog.status === 'active' ? drafts.push(blog) : published.push(blog)
  })

  return {published, drafts}
}

export const state = () => ({
  items: {
    drafts: [],
    published: []
  },
  item: {},
  isSaving: false
})

export const actions = {
  async createBlog({commit}, blogData) {
    commit('setIsSaving', true)
    console.log('instructor/blog.js actions createBlog call axios.$post->blogData')
    const blog = await this.$axios.$post('/api/v1/blogs', blogData)
    if(blog.isAxiosError === true){
      commit('setIsSaving', false)
      console.log(blog.data)
      return Error('')
    }
    console.log('instructor/blog.js actions createBlog done axios.$post->blogData')
    commit('setIsSaving', false)
    return blog
  },
  async fetchBlogById({commit}, blogId) {
    console.log('instructor/blog.js actions fetchBlogById call axios.$get->blogId')
    const blog = await this.$axios.$get(`/api/v1/blogs/${blogId}`)
    if(blog.isAxiosError === true){
      console.log(blog.data)
      return Error('')
    }
    console.log('instructor/blog.js actions fetchBlogById done axios.$get->blogId')
    console.log('blog.js mutations call setBlog')
    commit('setBlog', blog)
    console.log('blog.js mutations done setBlog')
  },
  async fetchUserBlogs({commit, state}) {
    const blogs = await this.$axios.$get('/api/v1/blogs/me')
    if(blogs.isAxiosError === true){
      console.log(blog.data)
      return Error('')
    }
    const { published, drafts } = separateBlogs(blogs)
    commit('setBlogs', {resource: 'drafts', items: drafts})
    commit('setBlogs', {resource: 'published', items: published})
    return { published, drafts }
  },
  async deleteBlog({commit, state}, blog) {
    const resource = blog.status === 'active' ? 'drafts' : 'published'
    const result = this.$axios.$delete(`/api/v1/blogs/${blog._id}`)
    if(result.isAxiosError === true){
      console.log(result.data)
      return Error('')
    }
    const index = state.items[resource].findIndex((b) => b._id === blog._id )
    commit('deleteBlog', {resource, index})
    return true
  },

  async updatePublishedBlog({commit, state}, {id, data}) {
    const blog = await this.$axios.$patch(`/api/v1/blogs/${id}`, data)
    if(blog.isAxiosError === true){
      console.log(blog.data)
      return Error('')
    }
    const index = state.items['published'].findIndex(b => b._id === id)
    commit('setPublishedBlog', {index, blog})
    return blog
  },

  async updateBlog({commit, state}, {data, id}) {
    console.log('instructor/blog.js actions updateBlog call axios.$patch-> Id, data')
    const blog = await this.$axios.$patch(`/api/v1/blogs/${id}`, data)
    if(blog.isAxiosError === true){
      console.log(blog.data)
      return blog
    }
    console.log('instructor/blog.js actions updateBlog done axios.$patch-> Id, data')
    console.log('courses.js mutations call setBlog')
    commit('setBlog', blog)
    console.log('courses.js mutations done setBlog')
    return state.item
  }
}

export const mutations = {
  setBlog(state, blog) {
    state.item = blog
  },
  setPublishedBlog(state, {index, blog}) {
    // Vue는 배열에 대해 다음과 같은 변경 사항을 감지할 수 없습니다.
    // 인덱스로 배열에 있는 항목을 직접 설정하는 경우, 예: vm.items[indexOfItem] = newValue
    // 배열 길이를 수정하는 경우, 예: vm.items.length = newLength
    Vue.set(state.items.published, index, blog)
  },
  setBlogs(state, {resource, items}) {
    state.items[resource] = items
  },
  deleteBlog(state, {resource, index}) {
    state.items[resource].splice(index, 1)
  },
  setIsSaving(state, isSaving) {
    state.isSaving = isSaving
  }
}