import UserAvatar from '../user_avatar/user_avatar.vue'
import UserListPopover from '../user_list_popover/user_list_popover.vue'
import StillImage from '../still-image/still-image.vue'

import { toRaw } from 'vue'

const EMOJI_REACTION_COUNT_CUTOFF = 12

const findEmojiByReplacement = (state, replacement) => {
  const allEmojis = state.instance.emoji.concat(state.instance.customEmoji)
  return allEmojis.find(emoji => emoji.replacement === replacement)
}

const EmojiReactions = {
  name: 'EmojiReactions',
  components: {
    UserAvatar,
    UserListPopover,
    StillImage
  },
  props: ['status'],
  data: () => ({
    showAll: false
  }),
  computed: {
    tooManyReactions () {
      return this.status.emoji_reactions.length > EMOJI_REACTION_COUNT_CUTOFF
    },
    showMoreString () {
      return `+${this.status.emoji_reactions.length - EMOJI_REACTION_COUNT_CUTOFF}`
    },
    accountsForEmoji () {
      return this.status.emoji_reactions.reduce((acc, reaction) => {
        if (reaction.url) {
          acc[reaction.url] = reaction.accounts || []
        } else {
          acc[reaction.name] = reaction.accounts || []
        }
        return acc
      }, {})
    },
    timelineStyle () {
      return this.$store.getters.mergedConfig.timelineStyle
    },
    loggedIn () {
      return !!this.$store.state.users.currentUser
    },
    filteredReactions () {
      // this is fucking Jank.
      var finalReacts = this.emojiReactions()
      var tempList = []
      var reactionsFilterItems = this.$store.getters.mergedConfig.reactionsFilterItems.split("\n")
      if (reactionsFilterItems.length > 0 && finalReacts.length > 0) {
        reactionsFilterItems.forEach((item) => {
          var toPush = []
          finalReacts.forEach((react) => {
            var rawReact = toRaw(react)["name"]

            if (
                // match regex
                // >1 check is to prevent = just disabling all emoji reacts
                 item.charAt(0) == "=" && item.length > 1 && rawReact.match(item.substring(1))
                // match everything explicit, if there's an @
              || rawReact == item.match(/.*@.*/) ? item : null
                // match everything else
              || (rawReact.match(/.*@.*/) ? rawReact.split("@")[0] : rawReact) == item
            ) {
              toPush.push(react)
            }
          })

          toPush.forEach((nice) => {
            tempList.push(nice)
          })
        })
      }

      tempList.forEach((item) => {
        finalReacts.splice(finalReacts.indexOf(item), 1)
      })

      return finalReacts
    }
  },
  methods: {
    emojiReactions () {
      return this.showAll
        ? this.status.emoji_reactions
        : this.status.emoji_reactions.slice(0, EMOJI_REACTION_COUNT_CUTOFF)
    },
    toggleShowAll () {
      this.showAll = !this.showAll
    },
    reactedWith (emoji) {
      return this.status.emoji_reactions.find(r => r.name === emoji).me
    },
    fetchEmojiReactionsByIfMissing () {
      const hasNoAccounts = this.status.emoji_reactions.find(r => !r.accounts)
      if (hasNoAccounts) {
        this.$store.dispatch('fetchEmojiReactionsBy', this.status.id)
      }
    },
    reactWith (emoji) {
      this.$store.dispatch('reactWithEmoji', { id: this.status.id, emoji })
      const emojiObject = findEmojiByReplacement(this.$store.state, emoji)
      this.$store.commit('emojiUsed', emojiObject)
    },
    unreact (emoji) {
      this.$store.dispatch('unreactWithEmoji', { id: this.status.id, emoji })
    },
    emojiOnClick (emoji, event) {
      if (!this.loggedIn) return

      if (this.reactedWith(emoji)) {
        this.unreact(emoji)
      } else {
        this.reactWith(emoji)
      }
    }
  }
}

export default EmojiReactions
