<template>
  <div>
    <div v-if="!$fetchState.pending" class="playbutton">
      <template v-if="user && user.name">
        <NuxtLink class="playbutton__playbutton" to="/play">
          Play!
        </NuxtLink>
        <div class="playbutton__logout" @click="logout">
          Logout
        </div>
      </template>
      <form v-else v-on:submit="login">
        <input
          v-model="authCode"
          class="playbutton__authinput"
          type="text"
          size="6"
          maxlength="6"
          placeholder="code"
        />
        <input
          type="submit"
          value="Go"
          :class="[ 'playbutton__authbutton', { disabled: loginDisabled }]"
        />
        <div class="playbutton__errormessage" v-if="errorMessage">
          {{ errorMessage }}
        </div>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      authCode: '',
      errorMessage: '',
    }
  },
  async fetch() {
    this.$engine.fetchUserInfo()
  },
  computed: {
    loginDisabled() {
      return this.authCode.length < 6
    },
    user() {
      return this.$store.state.engine.user
    },
  },
  methods: {
    async login(e) {
      e.preventDefault()
      try {
        await this.$axios.$get(`/api/login?code=${this.authCode}`)
        this.$fetch()
      } catch(e) {
        this.errorMessage = 'login failed'
      }
      this.authCode = ''
    },
    async logout() {
      this.authCode = ''
      try {
        await this.$axios.$get('/api/logout')
        window.location.reload()
      } catch(e) {
        this.errorMessage = 'logout failed'
      }
    },
  },
}
</script>

<style lang="scss">
.playbutton {
  font-family: Dosis;
  font-weight: 800;
  font-size: 36px;
  text-align: center;

  &__playbutton {
    width: 200px;
    height: 48px;
    padding: 4px 36px;
    border: 4px solid #c0c060;
    border-radius: 8px;
    background-color: #40a020;
    color: #ffff80;

    &:hover {
      border-color: #ffffc0;
      background-color: #60c040;
      color: #ffffc0;
    }
  }

  &__logout {
    margin-top: 36px;
    font-size: 24px;
    cursor: pointer;

    &:hover {
      color: #c0c080;
    }
  }

  &__authinput {
    display: inline;
    height: 36px;
    border: 4px solid #c0c060;
    border-radius: 8px;
    font-family: Dosis;
    font-weight: 800;
    font-size: 24px;
  }

  &__authbutton {
    display: inline;
    width: 80px;
    height: 48px;
    border: 4px solid #c0c060;
    border-radius: 8px;
    background-color: #40a020;
    color: #ffff80;
    font-size: 24px;

    &.disabled,
    &:hover.disabled {
      border-color: #808030;
      background-color: #406020;
      color: #808060;
    }
    &:hover {
      background-color: #60c040;
      color: #ffffc0;
    }
  }

  &__errormessage {
    padding: 8px;
    font-size: 18px;
    color: #ff8080;
  }
}
</style>
