<style>
.limit{
  margin-top: 0.5rem;
  word-break: break-all;
}
.onsale {
  text-decoration: line-through;
}
</style>
<template>
  <main>
    <section v-if='$store.state.experimentsStore.marketplace' 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.marketplace" class='route_container user_route'>
      <div class="section profile-heading card">
        <div class="columns is-mobile is-multiline">
          <div class="column is-3">
            <figure class="image is-512 is-centered">
              <img v-if="user.picture !== 'default' && user.approved" width="512px" height="512px" :src="user.picture">
              <img v-if="user.picture === 'default' && $store.state.theme === 'light' && user.approved" width="512px" height="512px" src="https://cdn.kaverti.com/teams/unknown-light.png">
              <img v-if="user.picture === 'default' && $store.state.theme === 'dark' && user.approved" width="512px" height="512px" src="https://cdn.kaverti.com/teams/unknown-dark.png">
              <img v-if="$store.state.theme === 'light' && !user.approved" width="512px" height="512px" src="https://cdn.kaverti.com/teams/pending-light.png">
              <img v-if="$store.state.theme === 'dark' && !user.approved" width="512px" height="512px" src="https://cdn.kaverti.com/user/avatars/full/default.png">
            </figure>
          </div>
          <div class="column is-7">
            <p>
              <span class="title is-bold limit">{{user.name}}</span><br>
              <span class="subtitle limit">Created by <router-link :to="'/u/' + user.User.username"> @{{user.User.username}}</router-link></span>
              <br>
            </p>
            <p class="limit">
              {{user.description}}
              <br>
              Asset uploaded at {{user.createdAt | formatDate}}
            </p>
          </div>
          <div class="column" style="float: right">
            <p v-if="!user.saleEnabled" style="float: right;">This item costs <b>{{user.price}} Koins</b></p>
            <p v-if="user.saleEnabled" style="float: right;">This item costs <b class="onsale">{{user.price}}</b><b> {{user.salePrice}} Koins</b></p><br>
            <b-button @click="buyItem()" v-if="!purchased && !loading && !failStatus" style="float: right;">Buy item</b-button>
            <b-button disabled v-if="loading && !failStatus" style="float: right;">Loading purchase status</b-button>
            <b-button disabled v-if="purchased && !loading && !failStatus" style="float: right;">Item Owned</b-button>
            <b-button disabled v-if="failStatus" style="float: right;">Failed to load status</b-button>
            <b-tooltip v-if="user.limited && purchased && !loading && !failStatus" style="float: right;" label="You own this item, if you don't want it anymore, you can sell it and put it on the market, this is only available for Limited Edition items">
              <b-button @click="sellItem()" style="float: right;">Sell item</b-button>
            </b-tooltip>
          </div>
        </div>
      </div>
      <br>
      <div class="column">
        <b-button v-if="user.limited" class="menu_button" :key='"user-menu-item-wall"' @click='$router.push(`/m/${user.id}/auction`)'>
          Auction
        </b-button>
        <b-tooltip v-if="!user.limited" label="Only limited edition items support auctioning">
          <b-button disabled="disabled" class="menu_button disabled" :key='"user-menu-item-wall"'>
            Auction
          </b-button>
        </b-tooltip>
        <br/> <br/>
        <div class="column box">
          <router-view :username='username'></router-view>
        </div>
      </div>
    </div>
  </main>
</template>

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

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

      username: "unknown",
      buy: {
        loading: false
      },
      user: null,
      purchased: false,
      loading: true,
      failStatus: false,
      savings: 0,
    }
  },
  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: {
    buyItem () {
      this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'marketplace/purchase/' + this.user.id)
        .then(() => {
        this.buy.loading = false
          this.axios
            .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `marketplace/check/${this.$route.params.id}`)
            .then(res => this.purchased = res.data.purchased, this.loading = false)
      }).catch(e => {
        this.buy.loading = false

        AjaxErrorHandler(this.$store)(e)
      })
    },
    getPercentageChange() {
      const decreaseValue = this.user.price - this.user.salePrice;

      this.savings = (decreaseValue / this.user.price) * 100;
    },
    resetFetchData () {
      this.offset = 0;
      this.users = [];

      this.fetchData();
    },
    fetchData () {
      this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `marketplace/view/${this.$route.params.id}`)
        .then(res => this.user = res.data)
    },
    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.fetchData()
    this.axios
      .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `marketplace/check/${this.$route.params.id}`)
      .then(res => this.purchased = res.data.purchased, this.loading = false)
  }
}
</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>
