<style>
.limit{
  margin-top: 0.5rem;
  word-break: break-all;
}
.team-img {
  border-radius: 50%;
}
.vertical {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.default-img {
  font-size: 80px;
}
</style>
<template>
  <main>
    <modal-window v-model='inviteModal' @click.stop='() => {}'>
      <div slot="header">
        <p>Invite people to {{user.name}}</p>
      </div>
      <div slot='main' class="modal-card-body">
        <b-field label="Amount of uses (0 is Unlimited)">
          <b-input :value="invite.maxUses" v-model="invite.maxUses">
          </b-input>
        </b-field>
        <b-button @click="generateInvite()">Refresh</b-button>
        <b-field label="Invite URL">
          <b-input
            :value="'https://kaverti.com/invite/' + invite.code"
            placeholder="Loading"
            disabled="disabled">
          </b-input>
        </b-field>
      </div>
      <button slot='footer' class='button button--modal' @click.stop='setShareModalState(false)'>OK</button>
    </modal-window>
    <section v-if="!$store.state.experimentsStore.teams" class="hero is-info is-large">
      <div class="hero-body">
        <div class="container">
          <h2>
            Kaverti Teams
          </h2>
          <h1>
            Kaverti Teams are coming soon
          </h1>
          <h2 v-if="$store.state.developerMode">
            However, you're currently opted into Experiments, you can enable the Teams experiment in User Settings.
          </h2>
        </div>
      </div>
    </section>
    <section v-if='$store.state.experimentsStore.teams' class="hero is-info">
      <div class="hero-body" style="padding: 1rem 1rem !important;">
        <div class="mobile-container">
          <div class="container">
            <p style="text-align: center;">Teams are currently in development, expect missing features.</p>
          </div>
        </div>
      </div>
    </section>
  <div v-if="$store.state.experimentsStore.teams" class='route_container user_route'>
    <div class="section profile-heading card">
      <div class="columns is-mobile is-multiline">
        <div class="column is-2">
          <figure class="image is-256 is-centered">
            <img class="team-img" v-if="user.picture !== 'default' && user.approved" width="256px" height="256px" :src="user.picture">
            <img class="team-img" v-if="user.picture === 'default' && $store.state.theme === 'light' && user.approved" width="256px" height="256px" src="https://cdn.kaverti.com/teams/unknown-light.png">
            <img class="team-img" v-if="user.picture === 'default' && $store.state.theme === 'dark' && user.approved" width="256px" height="256px" src="https://cdn.kaverti.com/teams/unknown-dark.png">
            <img class="team-img" v-if="$store.state.theme === 'light' && !user.approved" width="256px" height="256px" src="https://cdn.kaverti.com/teams/pending-light.png">
            <img class="team-img" v-if="$store.state.theme === 'dark' && !user.approved" width="256px" height="256px" src="https://cdn.kaverti.com/teams/pending-dark.png">
          </figure>
        </div>
        <div class="column is-7">
          <p>
            <span class="title is-bold limit">{{user.name}}&nbsp;<b-tooltip v-if="user.banned" class="is-danger" label="Team is banned and cannot be interacted with."><b-tag v-if="user.banned" class="is-danger">BANNED</b-tag></b-tooltip></span><br>
            <span class="subtitle limit">@{{user.username}}</span>
            <br>
          </p>
          <p class="limit">
            {{user.description}}
            <br>
            Team founded at {{user.createdAt | formatDate}}
          </p>
        </div>
        <div class="column" style="float: right">
          <b-tooltip style="float: right;" v-bind:label="user.name  + ' has join requests disabled, you can only be added by the owner, or someone with add privileges' ">
            <b-button v-if="$store.state.username && !$store.state.UserId === user.OwnerId" @click="joinTeam()" style="float: right;">Join team</b-button>
          </b-tooltip>
          <b-button v-if="$store.state.username && $store.state.UserId === user.OwnerId" class="button is-primary" style="float: right" @click='$router.push(`/team/${user.username}`)'>
            Edit Team
          </b-button>
          <b-button v-if="$store.state.username && $store.state.UserId !== user.OwnerId && !joined" class="button is-primary" style="float: right" @click='joinTeam()'>
            Join Team
          </b-button>
          <b-button v-if="$store.state.username && $store.state.UserId !== user.OwnerId && joined" class="button is-danger" style="float: right" @click='leaveTeam()'>
            Leave Team
          </b-button>
          <br><br>
          <b-button v-if="joined" style="float: right" @click="generateInvite()">
            Invite
          </b-button>
        </div>
      </div>
    </div>
    <br>
    <div class="column">
      <b-button v-if="!user.userWallOptOut && $store.state.username" class="menu_button" :key='"user-menu-item-wall"' @click='$router.push(`/t/${username}/wall`)'>
        Team Wall
      </b-button>
      <b-tooltip v-if="!user.userWallOptOut && !$store.state.username" label="You can only view a team's wall when logged in">
        <b-button v-if="!user.userWallOptOut && !$store.state.username" disabled="disabled" class="menu_button disabled" :key='"user-menu-item-wall"'>
          Team Wall
        </b-button>
      </b-tooltip>
      <b-button class="menu_button" :key='"user-menu-item-posts"' @click='$router.push(`/t/${username}/items`)'>
        Items
      </b-button>
      <b-button class="menu_button" :key='"user-menu-item-posts"' @click='$router.push(`/t/${username}/members`)'>
        Members and Roles
      </b-button>
      <br/> <br/>
      <div class="column box">
        <router-view :username='username'></router-view>
      </div>
    </div>
  </div>
  </main>
</template>

<script>
import MenuButton from '../MenuButton'
import ModalWindow from "@/components/ModalWindow";
import AjaxErrorHandler from "@/assets/js/errorHandler";

export default {
  name: 'Team',
  // eslint-disable-next-line vue/no-unused-components
  components: {MenuButton, ModalWindow},
  data () {
    return {
      menuItems: [
        /* { name: 'Wall', route: 'wall' }, */
        { name: 'Posts', route: 'posts' },
        { name: 'Threads', route: 'threads' },
        /* { name: 'Friends', route: 'friends' } */
      ],
      selected: 0,

      username: this.$route.params.username,
      user: null,
      relationship: false,
      joined: false,
      inviteModal: false,
      invite: {
        code: '',
        maxUses: 0
      },
      relationships: {
        type: ''
      }
    }
  },
  watch: {
    $route (to) {
      this.selected = this.getIndexFromRoute(to.path)
    }
  },
  computed: {
    userColor () {
      if(this.user) {
        return this.user.color
      } else {
        return null
      }
    },
    userPicture () {
      if(this.user && this.user.picture) {
        return 'https://cdn.kaverti.com/user/avatars/full/' + this.user.picture + '.png'
      } else {
        return null
      }
    }
  },
  methods: {
    resetFetchData () {
      this.offset = 0;
      this.users = [];

      this.fetchData();
    },
    fetchData () {
      this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
        .then(res => this.user = 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)
          }
        })
    },
    leaveTeam () {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/leave/' + this.user.username)
        .then(() => {
          this.axios
            .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/check/' + this.$route.params.username)
            .then(res => {
              this.joined = res.data.success
            })
        })
        .catch(e => {
          AjaxErrorHandler(this.$store)(e)
          this.axios
            .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/check/' + this.$route.params.username)
            .then(res => {
              this.joined = res.data.success
            })
        })
    },
    generateInvite () {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/admin/' + this.user.username + '/invites/create', {
          maxUses: this.invite.maxUses
        })
        .then(res => {
          this.invite.code = res.data.code
          this.inviteModal = true
        }).catch(e => {
          AjaxErrorHandler(this.$store)(e)
        })
    },
    joinTeam () {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/join/' + this.user.username)
        .then(() => {
          this.axios
            .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/check/' + this.$route.params.username)
            .then(res => {
              this.joined = res.data.success
            })
        })
        .catch(e => {
          AjaxErrorHandler(this.$store)(e)
          this.axios
            .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/check/' + this.$route.params.username)
            .then(res => {
              this.joined = res.data.success
            })
        })
    },
    getIndexFromRoute (path) {
      let selectedIndex
      let route = path.split('/')[3]

      this.menuItems.forEach((item, index) => {
        if(item.route === route) {
          selectedIndex = index
        }
      })

      return selectedIndex
    }
  },
  created () {
    this.resetFetchData()
    this.selected = this.getIndexFromRoute(this.$route.path)

    this.axios
      .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
      .then(res => this.user = res.data)
    this.axios
      .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/check/' + this.$route.params.username)
      .then(res => {
        this.joined = res.data.success
      })
  }
}
</script>

<style lang='scss' scoped>
@import '../../assets/scss/variables.scss';

.user_route {
  width: 70%;
}

.user_header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 1.5rem;
  background-color: #fff;
  padding: 1rem;
  border-radius: 0.25rem;
  border: thin solid $color__gray--darker;

  @at-root #{&}__icon {
    height: 128px;
    width: 128px;
    line-height: 5.5rem;
    @include text($font--role-emphasis, 5rem);
    text-align: center;
    background-color: $color__gray--darkest;
    color: #fff;
  }
  @at-root #{&}__info {
    display: flex;
    flex-direction: column;
    margin-left: 1rem;
    width: calc(100% - 6rem);
  }
  @at-root #{&}__username {
    margin-top: -0.25rem;
    font-size: 2rem;
    font-weight: bold
  }
  @at-root #{&}__date {
    color: $color__darkgray--primary;
    font-size: 1.5rem;
  }
}
.user_description {
  white-space: pre-line;
  margin-top: 0.5rem;
}
.user__view_holder {
  display: flex;
  flex-direction: row;
}
.user__links {
  width: 8rem;
  display: table;

  @at-root #{&}__menu_item {
    cursor: pointer;
    margin-bottom: 0.5rem;
    position: relative;

    &:hover { color: $color__darkgray--primary; }

    @at-root #{&}--selected {
      font-weight: bold;
    }
  }
}
.menu_button {
  margin: 2px;
}
.user__view {
  flex-grow: 1;
  width: 0;
}

@media (max-width: $breakpoint--tablet) {
  .user_route {
    width: inherit;
    overflow-x: hidden;
  }
  .user__view_holder {
    flex-direction: column;
  }
  .user_header {
    @at-root #{&}__icon {
      height: 256px;
      width: 256px;
    }
    @at-root #{&}__username {
      font-size: 1.75rem;
    }
    @at-root #{&}__date {
      font-size: 1.25rem;
    }
  }
  .user__links {
    display: flex;
    flex-direction: row;

    @at-root #{&}__menu_item {
      margin-right: 0.5rem;

      &:hover {
        color: $color__text--primary;
      }

      @at-root #{&}--selected::before {
        width: 100%;
        height: 0.2rem;
        left: 0rem;
        top: auto;
        border-radius: 1rem;
        bottom: -0.375rem;
      }
    }
  }
  .user__view {
    width: auto;
  }
}
</style>
