import generateProfileLink from 'src/services/user_profile_link_generator/user_profile_link_generator'
import { library } from '@fortawesome/fontawesome-svg-core'
import theoryImage from '../../assets/theorytoe.png'
import theoryUnreadImage from '../../assets/theorytoe-unread.png'
import {
  faBullhorn,
  faTimes
} from '@fortawesome/free-solid-svg-icons'

library.add(
  faBullhorn,
  faTimes
)

const shoutPanel = {
  props: ['floating', 'hide-theory'],
  data () {
    return {
      currentMessage: '',
      last: null,
      channel: null,
      collapsed: true
    }
  },
  computed: {
    messages () {
      return this.$store.state.shout.messages
    },
    unread () {
      return this.last !== this.$store.state.shout.last
    },
    theoryImage () {
      return this.unread ? theoryUnreadImage : theoryImage
    }
  },
  methods: {
    submit (message) {
      this.$store.state.shout.channel.push('new_msg', { text: message }, 10000)
      this.currentMessage = ''
    },
    togglePanel () {
      this.collapsed = !this.collapsed
      this.updateLast()
    },
    updateLast () {
      if (this.$store.state.shout.messages) {
        this.last = this.$store.state.shout.messages[this.$store.state.shout.messages.length - 1].id
      }
    },
    userProfileLink (user) {
      return generateProfileLink(user.id, user.username, this.$store.state.instance.restrictedNicknames)
    }
  },
  watch: {
    messages (newVal) {
      const scrollEl = this.$el.querySelector('.chat-window')
      if (!scrollEl) {
        if (this.last == null) {
          this.updateLast()
        }
        return
      }

      if (scrollEl.scrollTop + scrollEl.offsetHeight + 20 > scrollEl.scrollHeight) {
        this.$nextTick(() => {
          if (!scrollEl) return

          scrollEl.scrollTop = scrollEl.scrollHeight - scrollEl.offsetHeight
        })
      }

      this.updateLast()
    }
  }
}

export default shoutPanel
