<style>
  .limit{
    margin-top: 0.5rem;
    word-break: break-all;
  }
</style>
<template>
	<div class='route_container user_route columns'>
      <div class="column is-4" style="float: left">
        <div class="box has-text-centered">
          <div class="columns is-vcentered is-mobile">
            <div class="column is-narrow"><h1 class="title">{{username}}</h1></div>
            <tooltips>
              <b-tooltip style="padding-left: 2px; padding-right: 2px;" v-if='user && user.system' class="is-success" label="This user is a system user operated by administrators that mainly run API operations.">
                <b-tag rounded class="is-success">SYSTEM&nbsp;<i class="fas fa-info-circle"></i>&nbsp;</b-tag>
              </b-tooltip>
              <b-tooltip style="padding-left: 2px; padding-right: 2px;" v-if='user && user.bot' class="is-info" label="This user is a bot account that can run automated API operations.">
                &nbsp;
                <b-tag rounded class="is-info">BOT&nbsp;<i class="fas fa-info-circle"></i>&nbsp;</b-tag>
                &nbsp;
              </b-tooltip>
              <b-tooltip class="is-light" label="User is boosting the Kaverti Discord server.">
                <b-tag class="is-light" rounded v-if='user && user.booster'>BOOSTER&nbsp;<i class="fas fa-info-circle"></i></b-tag>
              </b-tooltip>
              <b-tooltip style="padding-left: 2px; padding-right: 2px;" v-if='user && user.admin' class="is-danger" label="User is an official Kaverti administrator.">
                &nbsp;
                <b-tag rounded class="is-danger">ADMIN&nbsp;<i class="fas fa-info-circle"></i>&nbsp;</b-tag>
                &nbsp;
              </b-tooltip>
              <b-tooltip style="padding-left: 2px; padding-right: 2px;" v-if='user && user.hidden' class="is-info" label="User is not discoverable in the user list.">
                &nbsp;
                <b-tag rounded>HIDDEN&nbsp;<i class="fas fa-info-circle"></i>&nbsp;</b-tag>
                &nbsp;
              </b-tooltip>
            </tooltips>
          </div>
          <img width=65% style="padding-top: 10px; padding-bottom: 10px;"
               :src = userPicture
          >
          <div class='user_description limit' v-if='user && user.description && user.description.length' v-html='user.description'></div>
          <br>
          <div v-if='user'>User was created on: {{user.createdAt | formatDate('date') }}</div>
          <div v-if='user && $store.state.developerMode'>UID: {{user.id}}</div>
          <br>
          <menu-button
            v-if='$store.state.admin'
            :options='[
					{ event: "scrub_username", value: "Scrub Username" },
					{ event: "scrub_desc", value: "Scrub Description" }
					]'
            @scrub_desc='scrubDesc'
            @scrub_username='scrubUsername'
          >
            <button class='button button--thin_text'>
              <font-awesome-icon :icon='["fa", "cog"]' style='margin-right: 0.25rem;' />
              Manage user
            </button>
          </menu-button><br>
          <b-button v-if="$store.state.experimentsStore.relationships && relationship && user.username !== $store.state.username && $store.state.username" class='is-danger button' icon-left="minus">
            Remove Friend
          </b-button>
          <b-button :value="1" @click="doRelationship" v-if="$store.state.experimentsStore.relationships && user && !relationship && user.username !== $store.state.username && $store.state.username" class='is-info button' icon-left="plus">
            Send friend request
          </b-button>
        </div>
      </div>
    <div class="column is-8-fullhd">
      <b-button v-if="!user.userWallOptOut && $store.state.username" class="menu_button" :key='"user-menu-item-wall"' @click='$router.push(`/user/${username}/wall`)'>
        User Wall
      </b-button>
      <b-tooltip v-if="!user.userWallOptOut && !$store.state.username" label="You can only view a user'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"'>
          User Wall
        </b-button>
      </b-tooltip>
      <b-button class="menu_button" :key='"user-menu-item-posts"' @click='$router.push(`/u/${username}/posts`)'>
        Posts
      </b-button>
      <b-button class="menu_button" :key='"user-menu-item-threads"' @click='$router.push(`/u/${username}/threads`)'>
        Threads
      </b-button>
      <b-button class="menu_button" :key='"user-menu-item-threads"' @click='$router.push(`/u/${username}/items`)'>
        Marketplace Items
      </b-button>
      <b-button class="menu_button" :key='"user-menu-item-threads"' @click='$router.push(`/u/${username}/inventory`)'>
        Inventory
      </b-button>
      <br/> <br/>
      <div class="column box">
      <router-view :username='username'></router-view>
      </div>
    </div>
  </div>
</template>

<script>
	import AjaxErrorHandler from '../../assets/js/errorHandler'
  import MenuButton from '../MenuButton'

  export default {
		name: 'user',
    components: {MenuButton},
		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,
        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 + `/` + `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)
            }
          })
      },
      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))
      },
      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))
      },
      doRelationship () {
        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'relationships/' + this.user.username, {
            type: this.relationships.type
          })
          .then(() => {
            this.description.loading = false
          })
          .catch(e => {
            this.description.loading = false

            AjaxErrorHandler(this.$store)(e, error => {
              this.description.error = error.message
            })
          })
      },
			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 + `/` + `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/${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>

<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: 6rem;
			width: 6rem;
			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: 250px;
				width: 50px;
			}
			@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>
