<!--
   Copyright 2018 Brigham Young University

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<template>
  <div class="wrapper">
    <template v-if="!hideAssignee">
      <span v-if="!assignedUser"></span>
      <span v-else-if="assignedUser.name === 'Unassigned'">Unassigned</span>
      <span v-else-if="assignedUser.name">Assigned to: {{assignedUser.name}}</span>
      <span v-else-if="assignedUser">Assigned</span>
      <span v-else></span>
    </template>
    <button :class="`btn btn-sm btn-outline-${buttonColor}`" @click="openReassign">
      <font-awesome-icon :icon="forwardIcon"/>
      Reassign
    </button>
  </div>
</template>
<script>
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faReply } from '@fortawesome/free-solid-svg-icons'

import { mapGetters } from 'vuex'

export default {
  name: 'AssignmentSummary',
  components: {
    FontAwesomeIcon
  },
  props: {
    hideAssignee: Boolean,
    buttonColor: { type: String, default: 'light' }
  },
  computed: {
    ...mapGetters(['flags', 'usersById']),
    forwardIcon() {
      return faReply
    },
    assignedUser() {
      const flags = this.flags.filter(f => f.isActive).filter(f => /^[0-9]{9}$/.test(f.value) || /^UNASSIGNED$/.test(f.value))
      if (flags.length > 1) {
        console.error('Double assignment?')
      } else if (flags.length === 0) {
        return null
      }
      const flag = flags[0]
      const user = /^UNASSIGNED$/.test(flag.value) ? { name: 'Unassigned' } : this.usersById(flag.value)
      return user
    }
  },
  methods: {
    openReassign () {
      const assignedTo = this.assignedUser ? this.assignedUser.byuId : undefined
      this.$modal.show('assignment-modal', { assignedTo })
    }
  }
}
</script>
<style scoped>
.wrapper {
  padding: 0.5rem;
}
</style>
