<style>
.team-img {
  border-radius: 50%;
}
.vertical-alt {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.limit{
  margin-top: 0.5rem;
  word-break: break-all;
}
</style>
<template>
  <main>
    <modal-window v-model='showRoleModifyModal' :loading='loading' style='z-index: 99; '>
      <div slot="header">
        Modifying {{role.name}}&nbsp;<b-tooltip class="is-info" label="From here you can modify a Team Role">
        <b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag>
      </b-tooltip>
      </div>
      <div slot='main' class="card-content">
        <div>
          Name of your role:
          <b-input maxlength="20" v-model="role.name"></b-input>
          <p>Permissions:</p>
          <b-switch type="is-info" v-model="role.administrator">
            Administrator
          </b-switch>
          <b-switch type="is-info" v-model="role.inviteUsers">
            Invite users
          </b-switch>
          <b-switch type="is-info" v-model="role.changeTeamMeta">
            Modify general Team settings
          </b-switch>
          <b-switch type="is-info" v-model="role.forumAdministrator">
            Modify Team Forum <b-tooltip class="is-info" label="Team forums are coming soon, you can set this for the future when they do release."><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <b-switch type="is-info" v-model="role.moderateForumThreads">
            Forum moderator <b-tooltip class="is-info" label="Team forums are coming soon, you can set this for the future when they do release. This role only allows people with the permission to delete threads and posts, not have access to forum settings"><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <b-switch type="is-info" v-model="role.submitTeamItems">
            Submit Marketplace items <b-tooltip class="is-info" label="Team Marketplace items are coming soon, you can set this for the future when they do release."><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <br>
          Please set a priority value <b-tooltip class="is-info" label="Priority values are how high the role is considered when taking actions and displaying users in some places. For example, the Admin role can be a priority of 1 (most important), and the Moderator role can be a priority of 2, etc"><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          <br>
          <b-numberinput v-model="role.priority"></b-numberinput>
        </div>
      </div>
      <div slot='footer'>
        <button class='button is-info' :loading="role.loading" @click='updateRole(role)'>Add Role</button>
      </div>
    </modal-window>
    <modal-window v-model='showRoleModal' :loading='loading' style='z-index: 99; '>
      <div slot="header">
        Creating a role&nbsp;<b-tooltip class="is-info" label="From here you can create a Team Role">
        <b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag>
      </b-tooltip>
      </div>
      <div slot='main' class="card-content">
        <div>
          Name of your new role:
          <b-input v-model="tRole.name"></b-input>
          <p>Permissions:</p>
          <b-switch type="is-info" v-model="tRole.administrator">
            Administrator
          </b-switch>
          <b-switch type="is-info" v-model="tRole.inviteUsers">
            Invite users
          </b-switch>
          <b-switch type="is-info" v-model="tRole.changeTeamMeta">
            Modify general Team settings
          </b-switch>
          <b-switch type="is-info" v-model="tRole.forumAdministrator">
            Modify Team Forum <b-tooltip class="is-info" label="Team forums are coming soon, you can set this for the future when they do release."><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <b-switch type="is-info" v-model="tRole.moderateForumThreads">
            Forum moderator <b-tooltip class="is-info" label="Team forums are coming soon, you can set this for the future when they do release. This role only allows people with the permission to delete threads and posts, not have access to forum settings"><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <b-switch type="is-info" v-model="tRole.submitTeamItems">
            Submit Marketplace items <b-tooltip class="is-info" label="Team Marketplace items are coming soon, you can set this for the future when they do release."><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          </b-switch>
          <br>
          Please set a priority value <b-tooltip class="is-info" label="Priority values are how high the role is considered when taking actions and displaying users in some places. For example, the Admin role can be a priority of 1 (most important), and the Moderator role can be a priority of 2, etc"><b-tag class="is-info" rounded><i class="fas fa-info-circle"></i></b-tag></b-tooltip>
          <br>
          <b-numberinput v-model="tRole.priority"></b-numberinput>
        </div>
      </div>
      <div slot='footer'>
        <button class='button is-info' :loading="tRole.loading" @click='addRole()'>Add Role</button>
      </div>
    </modal-window>
    <div class="section">
      <div class="">
        <h1>Roles:</h1>
        <ul class="list-group mb-2">
          <draggable
            class="list-group"
            tag="ul"
            v-model="roles"
            v-bind="dragOptions"
          >
            <transition-group type="transition">
              <li
                class="list-group-item"
                v-for="role in roles"
                :key="role.id"
              >
                <i
                  aria-hidden="true"
                ></i>
                <b-tag class="is-large">{{ role.name }} <b-tag @click="toggleModifyModal(role)"><i @click="toggleModifyModal(role)" class="fas fa-pencil"></i></b-tag></b-tag>
              </li>
            </transition-group>
          </draggable>
        </ul>

        <b-button @click="saveRoles()">Save Role Order</b-button>
        &nbsp;
        <b-button class="is-info" @click="toggleRoleCreate()"><i class="fas fa-plus"></i> Add Role</b-button>
      </div>
    </div>
    <p name='fade' mode='out-in'>
    <center><loading-message key='loading' v-if='loading'></loading-message></center>
    <center><div class='overlay_message' v-if='!loading && !roles.length'>
      Something went wrong while loading the team roles, check your internet connection, or check the <a href="https://status.troplo.com">Service Status</a>
    </div></center></p>
  </main>
</template>
<script>
import LoadingMessage from '../LoadingMessage';
import ScrollLoad from '../ScrollLoad';
import ModalWindow from "@/components/ModalWindow";
import draggable from 'vuedraggable'
import throttle from 'lodash.throttle';
import AjaxErrorHandler from '../../assets/js/errorHandler';

export default {
  name: 'TeamRoles',
  components: {
    LoadingMessage,
    // eslint-disable-next-line vue/no-unused-components
    ScrollLoad,
    ModalWindow,
    draggable
  },
  data () {
    return {
      search: '',
      users: [],
      userRoles: [],
      roles: [],
      team: [],
      role: {
        name: '',
        id: '',

        loading: false,
        administrator: false,
        inviteUsers: true,
        changeTeamMeta: false,
        forumAdministrator: false,
        moderateForumThreads: false,
        changeTeamPrivacy: false,
        submitTeamItems: false,
        priority: null
      },

      loading: false,
      offset: 0,
      limit: 15,
      showTeamTab: 0,
      showRoleModal: false,
      createTeamModal: false,
      drag: false,
      showRoleModifyModal: false,
      tRole: {
        name: '',
        id: '',

        loading: false,
        administrator: false,
        inviteUsers: true,
        changeTeamMeta: false,
        forumAdministrator: false,
        moderateForumThreads: false,
        changeTeamPrivacy: false,
        submitTeamItems: false,
        priority: null
      },

      roleOptions: [
        { name: 'Admins', value: 'admin' },
        { name: 'Users', value: 'user' }
      ],
      roleSelected: ['admin', 'user'],

      tableSort: {
        column: 'username',
        sort: 'desc'
      }
    }
  },
  methods: {
    // eslint-disable-next-line no-unused-vars
    updateListSortOrder() {
      const newList = [...this.roles].map((item, index) => {
        const newSort = index + 1;
        item.priority = newSort;
        return item;
      });
      this.roles = newList;
    },
    toggleModifyModal (role) {
      this.role.id = role.id
      this.role.name = role.name
      this.role.administrator = role.administrator
      this.role.priority = role.priority
      this.role.inviteUsers = role.inviteUsers
      this.role.changeTeamMeta = role.changeTeamMeta
      this.role.forumAdministrator = role.forumAdministrator
      this.role.moderateForumThreads = role.moderateForumThreads
      this.role.submitTeamItems = role.submitTeamItems
      this.showRoleModifyModal = true
    },
    saveRoles() {
      this.updateListSortOrder()
      this.axios.put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/admin/roles/modify/` + this.$route.params.username, {
        roles: this.roles
      }).then(() => {
        this.tRole.loading = false
        this.closeAccountModal()
      }).catch(e => {
        this.tRole.loading = false
        AjaxErrorHandler(this.$store)(e)
      })
    },
    updateRole(role) {
      this.role.loading = true
      this.axios.put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/admin/roles/modify/` + this.$route.params.username + '/' + this.role.id, {
        name: role.name,

        administrator: role.administrator,
        inviteUsers: role.inviteUsers,
        changeTeamMeta: role.changeTeamMeta,
        forumAdministrator: role.forumAdministrator,
        moderateForumThreads: role.moderateForumThreads,
        submitTeamItems: role.submitTeamItems,
        priority: role.priority
      }).then(() => {
        this.role.loading = false
        this.closeModifyModal()
      }).catch(e => {
        this.role.loading = false
        AjaxErrorHandler(this.$store)(e)
      })
    },

    clearTeamErrors() {
      this.tcreateProd.errors.username = ''
      this.tcreateProd.errors.name = ''
    },
    closeAccountModal() {
      this.showRoleModal = false
    },
    closeModifyModal() {
      this.showRoleModifyModal = false
    },
    addRole() {
      this.tRole.loading = true

      this.axios.post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/admin/roles/create/` + this.$route.params.username, {
        name: this.tRole.name,

        administrator: this.tRole.administrator,
        inviteUsers: this.tRole.inviteUsers,
        changeTeamMeta: this.tRole.changeTeamMeta,
        forumAdministrator: this.tRole.forumAdministrator,
        moderateForumThreads: this.tRole.moderateForumThreads,
        changeTeamPrivacy: this.tRole.changeTeamPrivacy,
        submitTeamItems: this.tRole.submitTeamItems,
        priority: this.tRole.priority
      }).then(() => {
        this.tRole.loading = false
        this.closeAccountModal()
        this.fetchData()
      }).catch(e => {
        this.tRole.loading = false
        AjaxErrorHandler(this.$store)(e)
        this.fetchData()
      })
    },
    toggleRoleCreate() {
      this.tRole.name = null
      this.showRoleModal = true
    },
    fetchData () {
      if(this.offset === null) return;

      this.loading = true;
      this.axios
        .get( process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/view/' + this.$route.params.username + "/roles")
        .then(res => {
          this.roles = res.data.filter(role => role.priority);
          //this.roles.push(...res.data);
          this.loading = /*loading =*/ false;



          //If returned data is less than the limit
          //then there must be no more pages to paginate
          if(res.data.length < this.limit) {
            this.offset = null;
          } else {
            this.offset+= this.limit;
          }
        })
        .catch(e => {
          AjaxErrorHandler(this.$store)(e);
          this.loading = /*loading =*/ false;
        });
      this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
        .then(res => this.team = res.data)
        .catch(e => {
          let invalidId = e.response.data.errors.find(error => {
            return error.name === 'accountDoesNotExist'
          })

          if(invalidId) {
            this.$store.commit('set404Page', true)
          } else {
            AjaxErrorHandler(this.$store)(e)
          }
        })
    },
    resetFetchData () {
      this.offset = 0;
      this.users = [];

      this.fetchData();
    }
  },
  getNewerUsers () {
    this.loadingNewer = true

    this.axios
      .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/view/' + this.$route.params.username + "/members" + '?limit=' + this.newUsers)
      .then(res => {
        this.loadingNewer = false
        this.newUsers = 0

        this.threads.unshift(...res.data.Threads)
      })
      .catch((e) => {
        this.loadingNewer = false
        AjaxErrorHandler(this.$store)(e)
      })
  },
  mounted () {
    this.fetchData();
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost"
      };
    },
  },
  watch: {
    tableSort: 'resetFetchData',
    roleSelected: 'resetFetchData',
    search: throttle(function () {
      this.resetFetchData();
    }, 200)
  }
}
</script>
<style>
.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
.list-group {
  min-height: 20px;
}
.list-group-item {
  cursor: move;
}
.list-group-item i {
  cursor: pointer;
}
</style>
