<style>
.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;
}
.zoom_sp {
  transition: transform .2s;
}
.zoom_sp:hover {
  transform: scale(1.2);
  cursor: hand;
}

.wrapper {

}

.wrapper > div {
  border: 1px solid #000000;
  border-radius: 0px;
  padding: 1px;
  height: 32px;
  width: 32px;
}
.wrapper {
  display: grid;
  grid-template-columns: repeat(15, 1fr);
  grid-gap: 12px;
}
</style>
<template>
  <main>
    <div class="section 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"><h1 class="title">Your current avatar</h1></div>
          </div>
            <img width=60%
                 :src = '"http://localhost/user/avatars/full/" + this.user.picture + ".png"'

            />
          <br>
          <menu-button
            v-if='$store.state'
            :options='[
					{ event: "refresh", value: "Refresh Avatar" },
					{ event: "report_a_problem", value: "Report a problem" }
					]'
            @refresh='RefreshAvatar'
          >
            <button class='button button--thin_text'>
              <font-awesome-icon :icon='["fa", "cog"]' style='margin-right: 0.25rem;' />
              Problems with your avatar?
            </button>
          </menu-button>
          <br>
          Head:<br>
          <v-swatches
            v-model="user.headColor"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          Body:<br>
          <v-swatches
            v-model="user.color"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          Left arm:<br>
          <v-swatches
            v-model="user.leftArmColor"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          Right arm:<br>
          <v-swatches
            v-model="user.rightArmColor"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          Left leg:<br>
          <v-swatches
            v-model="user.leftLegColor"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          Right leg:<br>
          <v-swatches
            v-model="user.rightLegColor"

            show-fallback

            popover-x="left"
          ></v-swatches><br>
          <br><b-button class="is-info" @click="colorChanges" :loading="colorLoading">Save Changes</b-button>
        </div>
      </div>
      <div class="column is-6 box">
        <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;">Current limitations include only being able to put on 1 item per category at a time. So applying an item will replace the item applied if one is applied in the same category, and vice versa</p>
              </div>
            </div>
          </div>
        </section>
        <br>
        <tab-view
          :tabs='["Hats", "Faces", "Shirts", "Pants"]'
          v-model="tab"
          padding='true'
          slot='main'
        >
        </tab-view>
        <scroll-load
          key='user-row'
          class='columns is-multiline'
          v-if='users.length'
          :loading='loading'
        >
          <div class="column is-4" v-for='user in users' :key='"user-row" + user.Item.id' v-show="user.Item.ItemCategoryId === tab"><div class="card">
            <div class="card-content">
              <div class="media-left">
                  <img v-if=" user.Item.approved" width="128px" height="128px" :src="'http://localhost/marketplace/avatars/' + user.Item.previewFile + '.png'">
                  <img v-if="$store.state.theme === 'light' && !user.Item.approved" width="128px" height="128px" src="http://localhost/marketplace/pending-light.png">
                  <img v-if="$store.state.theme === 'dark' && !user.Item.approved" width="128px" height="128px" src="http://localhost/marketplace/pending-dark.png">
                  <img v-if="!$store.state.theme && !user.Item.approved" width="128px" height="128px" src="http://localhost/marketplace/pending-light.png">
              </div>
              <br>
              <div class="media">
                <div class="media-content">
                  <p class="title is-4"><router-link :to="'/m/' + user.Item.id">{{user.Item.name}}</router-link></p>
                  <p class="subtitle is-6">Created by <router-link :to="'/u/' + user.Item.User.username"> @{{user.Item.User.username}}</router-link></p>
                </div>
              </div>

              <div class="content limit">
                {{user.Item.description | truncate(70)}}
              </div>
              <b-button @click="apply(user)">Apply</b-button>
              <b-button @click="remove(user)">Remove</b-button>
            </div>
          </div>
          </div>
        </scroll-load>
        <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 && !users.length'>
          You have no Marketplace items
        </div></center></p>
      </div>
    </div>
  </main>
</template>
<script>
import LoadingMessage from '../LoadingMessage';
import ScrollLoad from '../ScrollLoad';
import MenuButton from '../MenuButton'
import TabView from '../TabView'
import 'vue-swatches/dist/vue-swatches.css'
import VSwatches from 'vue-swatches'
import AjaxErrorHandler from '../../assets/js/errorHandler';

export default {
  name: 'Inventory',
  components: {
    LoadingMessage,
    ScrollLoad,
    TabView,
    MenuButton,
    VSwatches
  },
  data () {
    return {
      search: '',
      users: [],
      user: null,
      tab: 0,

      loading: true,
      offset: 0,
      limit: 15,
      colorLoading: false,
      refreshAvatar: {
        loading: false,
        error: ''
      },

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

      tableSort: {
        column: 'username',
        sort: 'desc'
      }
    }
  },
  methods: {
    colorChanges () {
      this.colorLoading = true
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'avatar/colors', {
          headColor: this.user.headColor,
          color: this.user.color,
          leftArmColor: this.user.leftArmColor,
          rightArmColor: this.user.rightArmColor,
          leftLegColor: this.user.leftLegColor,
          rightLegColor: this.user.rightLegColor
        })
        .then(() => {
          this.colorLoading = false
          this.axios
            .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/render/refresh', {
            })
            .then(() => {
              this.resetFetchData()
              this.refreshAvatar.loading = false
            })
            .catch(e => {
              this.refreshAvatar.loading = false

              AjaxErrorHandler(this.$store)(e, error => {
                this.refreshAvatar.error = error.message
              })
            })
        })
    },
    remove (user) {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'marketplace/remove/' + user.Item.id, {
        })
        .then(() => {
          this.axios
            .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/render/refresh', {
            })
            .then(() => {
              this.resetFetchData()
              this.refreshAvatar.loading = false
            })
            .catch(e => {
              this.refreshAvatar.loading = false

              AjaxErrorHandler(this.$store)(e, error => {
                this.refreshAvatar.error = error.message
              })
            })
        })
    },
    apply (user) {
      this.axios
        .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'marketplace/apply/' + user.Item.id, {
        })
        .then(() => {
          this.axios
            .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/render/refresh', {
            })
            .then(() => {
              this.resetFetchData()
              this.refreshAvatar.loading = false
            })
            .catch(e => {
              this.refreshAvatar.loading = false

              AjaxErrorHandler(this.$store)(e, error => {
                this.refreshAvatar.error = error.message
              })
            })
        })
        .catch(e => {
          this.refreshAvatar.loading = false

          AjaxErrorHandler(this.$store)(e, error => {
            this.refreshAvatar.error = error.message
          })
        })
    },
    RefreshAvatar () {
      this.axios
        .post(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'users/render/refresh', {
        })
        .then(() => {
          this.refreshAvatar.loading = false
          this.resetFetchData()
        })
        .catch(e => {
          this.refreshAvatar.loading = false
          this.resetFetchData()

          AjaxErrorHandler(this.$store)(e, error => {
            this.refreshAvatar.error = error.message
          })
        })
    },
    fetchData () {
      this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `userinfo`)
        .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)
          }
        })
      if(this.offset === null) return;

      let url = process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'inventory'
      if(this.roleSelected.length === 1) {
        url += '&role=' + this.roleSelected[0];
      }
      if(this.search.length) {
        url += '&search=' + encodeURIComponent(this.search.trim());
      }

      this.loading = true;
      this.axios
        .get(url)
        .then(res => {
          this.users.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;
        });
    },
    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 + '/' + 'inventory' + '?limit=' + this.newUsers)
      .then(res => {
        this.loadingNewer = false
        this.newUsers = 0

        this.threads.unshift(...res.data)
      })
      .catch((e) => {
        this.loadingNewer = false
        AjaxErrorHandler(this.$store)(e)
      })
  },
  mounted () {
    this.fetchData();
  }
}
</script>
