import BasicUserCard from 'src/components/basic_user_card/basic_user_card.vue'
import ModerationTools from 'src/components/moderation_tools/moderation_tools.vue'
import Popover from 'src/components/popover/popover.vue'

import { forEach, every, findKey } from 'lodash'

import { library } from '@fortawesome/fontawesome-svg-core'
import {
  faFilter,
  faSearch
} from '@fortawesome/free-solid-svg-icons'

library.add(
  faFilter,
  faSearch
)

const UsersTab = {
  data () {
    return {
      searchTerm: null,
      page: 1,
      accountType: {
        local: true,
        external: false
      },
      status: {
        active: true,
        deactivated: false,
        need_approval: false,
        unconfirmed: false
      },
      actorType: {
        Person: false,
        Service: false,
        Application: false
      }
    }
  },
  components: {
    BasicUserCard,
    ModerationTools,
    Popover
  },
  created () {
    this.query()
  },
  computed: {
    users () { return this.$store.state.users.adminUsers },
    isActive () {
      const tabSwitcher = this.$parent
      return tabSwitcher ? tabSwitcher.isActive('users') : false
    }
  },
  methods: {
    all (filter) { return every(filter, _ => !_) },
    setAccountType (type = false) {
      forEach(this.accountType, (k, v) => { this.accountType[v] = false })
      if (type) {
        this.accountType[type] = true
      }

      this.page = 1
      this.query()
    },
    setStatus (status = false) {
      forEach(this.status, (k, v) => { this.status[v] = false })
      if (status) {
        this.status[status] = true
      }

      this.page = 1
      this.query()
    },
    setActorType (type = false) {
      forEach(this.actorType, (k, v) => { this.actorType[v] = false })
      if (type) {
        this.actorType[type] = true
      }

      this.page = 1
      this.query()
    },
    search () {
      this.page = 1
      this.query()
    },
    prevPage () {
      this.page--
      this.query()
    },
    nextPage () {
      this.page++
      this.query()
    },
    query () {
      const params = {}
      params.actorTypes = [findKey(this.actorType, _ => _)].filter(Boolean)
      params.filters = [
        findKey(this.status, _ => _),
        findKey(this.accountType, _ => _)
      ].filter(Boolean)

      if (this.searchTerm) {
        params.name = this.searchTerm
      }
      if (this.page > 1) {
        params.page = this.page
      }

      this.$store.dispatch('fetchUsers', params)
    }
  }
}

export default UsersTab
