<style>
.limit{
  margin-top: 0.5rem;
  word-break: break-all;
}
</style>
<template>
  <main class="section">
    <div class="columns is-centered">
      <div class="column is-4 is-vcentered has-text-centered">
        <h1 class="title">{{user.username}}&nbsp;<Badges :username="user.username" :system="user.system" :hidden="user.hidden" :admin="user.admin" :booster="user.booster" :bot="user.bot"></Badges></h1>
        <div class="box">
          <img :src="'https://cdn.kaverti.com/user/avatars/full/' + user.picture + '.png'" :alt="user.username + '\'s avatar'" width=25%>
        </div>
        <div class="buttons is-centered">
          <b-button @click="doRelationship" class="is-success" v-if="relationships.type === 'notFriends' && user.username !== $store.state.user.username"><i class="fas fa-plus"></i> &nbsp;{{$t('relationships.notFriends')}}</b-button>
          <b-button @click="removeFriend" class="is-warning" v-if="relationships.type === 'pending'"><i class="fas fa-minus"></i> &nbsp;{{$t('relationships.pending')}}</b-button>
          <b-button @click="doRelationshipAccept" class="is-info" v-if="relationships.type === 'pendingCanAccept'"><i class="fas fa-plus"></i> &nbsp;{{$t('relationships.pendingCanAccept')}}</b-button>
          <b-button @click="removeFriend" class="is-danger" v-if="relationships.type === 'ignore'"><i class="fas fa-minus"></i> &nbsp;{{$t('relationships.ignore')}}</b-button>
          <b-button @click="removeFriend" class="is-danger" v-if="relationships.type === 'accepted'"><i class="fas fa-minus"></i> &nbsp;{{$t('relationships.accepted')}}</b-button>
          <b-button class="is-info" v-if="relationships.type === ''" disabled><i class="fas fa-spin"></i> &nbsp;<i class="fas fa-circle-notch fa-spin"></i>&nbsp;{{ $t('generic.loading') }}</b-button>
        </div>
        <h1 class="subtitle">
          {{ $t('user.about') }} {{user.username}}
        </h1>
        <div class="box limit">
          <div v-if="user.description">{{ $t('user.description') }}: {{user.description}}</div><br>
          <div v-if="!user.description">{{$t('user.description')}}: {{$t('user.defaultDesc')}} {{user.username}}</div>
          {{ $t('user.created') }}: {{user.createdAt | formatDate()}}<br>
          {{ $t('user.marketplace') }}:
        </div>
      </div>
      <div class="column is-6 is-vcentered has-text-centered">
        <h1 class="title">{{ $t('user.more') }} {{user.username}}</h1>
        <div>

          <div class="tabs">
            <ul>
              <router-link tag="li" :to="'/u/' + user.username + '/wall'" exact><a>{{ $t('user.wall') }}</a></router-link>
              <router-link tag="li" :to="'/u/' + user.username + '/items'" exact><a>{{ $t('user.items') }}</a></router-link>
              <router-link tag="li" :to="'/u/' + user.username + '/inventory'" exact><a>{{ $t('user.inventory') }}</a></router-link>
              <router-link tag="li" :to="'/u/' + user.username + '/awards'" exact><a>{{ $t('user.awards') }}</a></router-link>
              <router-link tag="li" :to="'/u/' + user.username + '/wearing'" exact><a>{{ $t('user.wearing') }}</a></router-link>
              <router-link tag="li" :to="'/u/' + user.username + '/friends'" exact><a>{{ $t('user.relationships') }}</a></router-link>
            </ul>
          </div>
        </div>
        <div class="card">
          <div class="card-content">
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<script>
import AjaxErrorHandler from '../../assets/js/errorHandler'
import Badges from '../components/Badges'
export default {
  name: 'User',
  components: {
    Badges
  },
  data () {
    return {
      modifyUserModal: true,
      user: {
        username: "Loading",
        description: "Loading",
        createdAt: "2020-01-01T00:00:00.000Z"
      },
      relationship: false,
      relationships: {
        type: ''
      }
    }
  },
  watch: {
    '$route.params.username' () {
      this.user = [{
        username: "Loading",
        description: "Loading",
        createdAt: "2020-01-01T00:00:00.000Z"
      }]
      this.relationship = false
      this.relationships.type = ''
      this.fetchData()
    }
  },
  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 + `/` + `user/${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)
            }
          })
      this.axios
          .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + 'relationships/get/' + this.$route.params.username)
          .then(res => this.relationships.type = res.data.type)
    },
    scrubDesc () {
      this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'admin/user/scrub', {
            description: "descscram",
            user: this.username
          })
          .then(() => {
            this.resetFetchData()
          })
          .catch(AjaxErrorHandler(this.$store))
    },
    refreshAvatar () {
      this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'admin/user/avatar', {
            user: this.username
          })
          .then(() => {
            this.resetFetchData()
          })
          .catch(AjaxErrorHandler(this.$store))
    },
    scrubUsername () {
      this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'admin/user/scrub', {
            username: "usernamescram",
            user: this.username
          })
          .then(() => {
            this.description.loading = false
          })
          .catch(AjaxErrorHandler(this.$store))
    },
    refreshFriend() {
      this.relationships.type === ''
      this.axios
          .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
          .then(res => this.relationships.type = res.data.type)
    },
    removeFriend () {
      this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'relationships/remove', {
            friend: this.$route.params.username
          })
          .then(() => {
            this.refreshFriend()
            this.description.loading = false
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = res.data, this.refreshFriend())
                .catch(e => {
                  this.refreshFriend()
                  let invalidId = e.response.data.errors.find(error => {
                    return error.name === 'accountDoesNotExist'
                  })

                  if(invalidId) {
                    this.$store.commit('set404Page', true)
                  } else {
                    AjaxErrorHandler(this.$store)(e)
                  }
                })
          })
          .catch(e => {
            this.refreshFriend()
            this.description.loading = false

            AjaxErrorHandler(this.$store)(e, error => {
              this.description.error = error.message
            })
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = res.data, this.refreshFriend())
                .catch(e => {
                  this.refreshFriend()
                  let invalidId = e.response.data.errors.find(error => {
                    return error.name === 'accountDoesNotExist'
                  })

                  if(invalidId) {
                    this.$store.commit('set404Page', true)
                  } else {
                    AjaxErrorHandler(this.$store)(e)
                  }
                })
          })
    },
    doRelationship () {
      this.axios
          .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'relationships/send', {
            friend: this.$route.params.username
          })
          .then(() => {
            this.refreshFriend()
            this.description.loading = false
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = 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)
                  }
                })
          })
          .catch(e => {
            this.refreshFriend()
            this.description.loading = false

            AjaxErrorHandler(this.$store)(e)
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = 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)
                  }
                })
          })
    },
    doRelationshipAccept () {
      this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'relationships/accept', {
            friend: this.$route.params.username
          })
          .then(() => {
            this.refreshFriend()
            this.description.loading = false
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = 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)
                  }
                })
          })
          .catch(e => {
            this.refreshFriend()
            this.description.loading = false

            AjaxErrorHandler(this.$store)(e, error => {
              this.description.error = error.message
            })
            this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
                .then(res => this.relationship = 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)
                  }
                })
          })
    },
    getIndexFromRoute (path) {
      let selectedIndex
      let route = path.split('/')[3]

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

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

    this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `user/${this.$route.params.username}`)
        .then(res => this.user = res.data)

    this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `relationships/get/${this.$route.params.username}`)
        .then(res => this.relationship = 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)
          }
        })
  }
}
</script>