<template>
  <q-page class="column no-wrap">
    <div class="bg-red col col-shrink" style="">
      <q-tabs
        v-model="tab"
        class="bg-grey-2"
        inline-label
        align="justify"
        active-bg-color="bg-grey-1"
        active-color="cyan-14"
        indicator-color="cyan-14"
        switch-indicator
      >
        <q-tab name="profile" label="Profil" icon="perm_identity"/>
        <q-tab v-if="boolAlreadyInTeam" name="teams" label="Team" icon="group"/>
      </q-tabs>
      <q-separator color="grey-4"/>
    </div>

    <div class="col flex column">
      <q-tab-panels v-model="tab" animated swipeable class="col">

        <q-tab-panel name="profile" class="fit q-pa-none">
          <div class="bg-primary q-pa-md">
            <p class="text-h3 text-white"> {{userName}} </p>
            <p class="text-white"> Meine Email: {{email}} </p>
            <p class="text-white"> Mein Rang: {{userRanking}} </p>
            <p class="text-white"> Mein Team: {{teamName}} </p>
          </div>
          <div class="q-pa-md">
            <div v-show="!boolAlreadyInTeam">
              <q-input lazy-rules outlined filled stack-label v-model="newTeamName"
                       type="text"
                       label="Teamname eingeben"
                       :rules="[val=>val.length>=2||'Name muss mindestens 5 Zeichen lang sein!']"/>
              <q-btn
                :disabled="!newTeamNameValidationSuccesful"
                label="Team anlegen"
                color="primary"
                class="full-width"
                @click="createTeam()"
                unelevated
              />
            </div>
            <p class="text-h5 q-mt-sm"> Teameinladungen </p>
            <q-list>
              <q-card class="q-mb-md" v-for="teamInvite in teamInvites" :key="teamInvite.id">
                <q-expansion-item
                  class=""
                  expand-icon-toggle
                  expand-separator
                  icon="group"
                  :label="teamInvite.team.name"
                  :caption="teamInvite.team.teamStatus"
                >
                  <q-item class="q-pr-sm reverse q-gutter-x-sm">
                    <q-btn :disabled="boolAlreadyInTeam" @click="joinTeam(teamInvite)" unelevated color="positive" stack
                           icon="arrow_forward"
                           label="Annehmen" size="sm"/>
                    <q-btn @click="deleteTeamInvite(teamInvite)" unelevated color="negative" stack icon="delete"
                           label="Ablehnen" size="sm"/>
                  </q-item>
                </q-expansion-item>
              </q-card>
            </q-list>
          </div>
        </q-tab-panel>
        <q-tab-panel v-if="boolAlreadyInTeam" name="teams" class="q-pa-none">
          <div class="bg-primary q-pa-md" v-show="boolAlreadyInTeam">
            <p class="text-h3 text-white"> {{teamName}} </p>
            <p class="text-white"> Unser Rang: {{teamRanking}} </p>
            <p v-show="!boolStatus" class="text-white">
              Unser Status: {{currentTeamStatus}}
              <q-btn icon="create"
                     class="on-right"
                     @click="updateStatus()"
                     color="amber"/>
            </p>
            <q-input v-show="boolStatus" lazy-rules outlined filled stack-label v-model="teamStatus"
                     type="text" label="Neuer Teamstatus" bg-color="white"
                     :rules="[val=>val.length<=160||'Status zu lang!']"/>
            <div v-show="boolStatus" align="center">
              <q-btn icon="done"
                     class="on-left"
                     :disabled="!teamStatusChecked"
                     @click="setTeamStatus()"
                     color="positive"
                     type="submit"/>
              <q-btn icon="clear"
                     class="on-right"
                     @click="updateStatus()"
                     color="negative"
                     type="submit"/>
            </div>
          </div>
          <div class="bg-white q-pa-md" v-show="boolAlreadyInTeam">
            <p class="text-h5"> Teammitglieder </p>
            <q-table
              v-if="boolTable"
              name="teamDataTable"
              :data="teamData"
              :columns="teamColumns"
              row-key="name"
              table-class="my-custom"
              hide-bottom
              :pagination.sync="pagination"
            />
            <br/>
            <div align="center">
              <q-btn label="Nutzer einladen"
                     @click="activateInvite()"
                     color="primary"
                     class="full-width"
                     type="submit"/>
            </div>
            <div align="center" class="row q-mt-sm">
              <q-input v-show="inviteActivated" lazy-rules outlined filled stack-label v-model="inviteMail"
                       type="text" label="Email des Nutzers" class="col-9"
                       :rules="[val=>validateEmail(val)||'Bitte Email verwenden']"/>
              <q-btn v-show="inviteActivated"
                     class="col-3"
                     icon="arrow_right_alt"
                     @click="sendTeamInvite()"
                     :disabled="!teamInviteChecked"
                     color="positive"
                     type="submit"/>
            </div>
            <div align="center" class="q-mt-sm">
              <q-btn label="Team verlassen"
                     @click="confirmLeave()"
                     color="negative"
                     class="full-width"
                     type="submit"/>
            </div>
            <br/>
          </div>
        </q-tab-panel>

      </q-tab-panels>
    </div>
  </q-page>

</template>

<style>
  /*.my-custom th {*/
  /*  color: #027BE3 !important;*/
  /*}*/

  /*.my-custom tr {*/
  /*  color: #027BE3 !important;*/
  /*}*/

  /*.my-custom td {*/
  /*  color: #027BE3 !important;*/
  /*}*/
</style>
<script>
  //import {dom} from 'quasar'
  //const {height, width} = dom
  export default {
    data() {
      return {
        tab: 'profile',
        inviteMail: "",
        currentTeamStatus: "",
        teamStatus: "",
        userName: "",
        email: null,
        userRanking: null,
        teamName: null,
        boolAlreadyInTeam: false,
        teamRanking: null,
        newTeamName: "",
        leaveTeamCheck: "",
        teamMembers: [],
        teamInvites: [],
        inviteActivated: false,
        boolStatus: false,
        boolTable: true,
        boolMemberTableUpdating: false,
        teamColumns: [
          {
            name: 'desc',
            label: 'Name',
            required: true,
            align: 'left',
            field: row => row.name,
            format: val => `${val}`,
          },
          {
            name: 'ranking',
            label: 'Rang',
            required: true,
            align: 'left',
            field: 'ranking',
            sortable: true,
          }
        ],
        teamData: [],
        pagination: {
          sortBy: 'ranking',
          descending: false,
          page: 1,
          rowsPerPage: 10
        },
      }
    },
    mounted: function () {
    },
    computed: {
      hasAdminState() {
        return this.$store.getters['auth/GET_ADMINSTATE'];
      },
      newTeamNameValidationSuccesful() {
        if (this.newTeamName.length >= 5) {
          return true;
        }
        return false;
      },
      teamInviteChecked() {
        if (this.validateEmail(this.inviteMail)) {
          return true;
        }
        return false;
      },
      teamStatusChecked() {
        if (this.teamStatus.length <= 160) {
          return true;
        }
        return false;
      },
      leaveConfirmed() {
        if (this.leaveTeamCheck === 'BESTÄTIGEN') {
          return true;
        }
        return false;
      }
    },
    created: function () {
      // this.$store.commit('auth/SET_AUTHENTICATED');
      // this.$store.commit('auth/SET_USER');
      this.userName = JSON.parse(localStorage.getItem('userToken')).name;
      this.email = JSON.parse(localStorage.getItem('userMail'));
      this.getPersonalRanking();
      this.updateTeamData();
    },
    methods: {
      confirmLeave() {
        this.$q.dialog({
          title: 'Verlassen...',
          message: 'Willst du dein aktuelles Team wirklich verlassen?',
          persistent: true,
          cancel: true,
        }).onOk(() => {
          console.log('>>>> OK');
          this.leaveTeam();
        }).onCancel(() => {
          console.log('>>>> Cancel')
        }).onDismiss(() => {
        })
      },
      activateInvite() {
        if (this.inviteActivated) {
          this.inviteActivated = false;
        } else {
          this.inviteActivated = true;
        }
      },
      updateStatus() {
        if (this.boolStatus) {
          this.boolStatus = false;
        } else {
          this.boolStatus = true;
        }
      },
      updateTable() {
        if (this.boolTable) {
          this.boolTable = false;
        } else {
          this.boolTable = true;
        }
      },
      validateEmail(email) {
        let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
      },
      getPersonalRanking() {
        let email = this.email;
        this.$axios.get('/api/getRankingPlace', {params: {email}})
          .then((response) => {
            this.userRanking = response.data;
          }).catch((error) => {
          this.handleError(error);
        })
      },
      async updateTeamData() {
        await this.getTeamData();
        this.boolTable = false;
        this.boolTable = await this.fetchTeamMembers();
        await this.fetchTeamInvites();
      },
      getTeamData() {
        return new Promise(resolve => {
          let token;
          if (localStorage.getItem('userToken')) {
            token = JSON.parse(localStorage.getItem('userToken')).token;
          } else {
            return;
          }
          this.$axios.get('/api/getTeamOfUser', {params: {token}})
            .then(response => {
              if (response.data === '') {
                this.boolAlreadyInTeam = false;
                this.teamName = "Aktuell in keinem Team";
                this.currentTeamStatus = "";
                this.teamRanking = "-";
              } else {
                this.boolAlreadyInTeam = true;
                this.teamName = response.data.name;
                this.currentTeamStatus = response.data.teamStatus;
                this.teamRanking = "-";
              }
              console.log("getTeam: " + response);
            }).catch((error) => {
            this.handleError(error);
          }).finally(() => resolve(true));
        })
      },
      createTeam() {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        params.name = this.newTeamName;
        this.$axios.post('/api/createTeam', null, {params})
          .then((response) => {
            console.log("createTeam: " + response);
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Das Team " + this.newTeamName + " wurde erfolgreich erstellt!",
              title: "Teamerstellung",
              color: "blue"
            });
            this.updateTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      leaveTeam() {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        this.$axios.put('/api/leaveTeam', null, {params})
          .then((response) => {
            console.log("createTeam: " + response);
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Du hast das Team " + this.teamName + " verlassen!",
              title: "Team verlassen",
              color: "blue"
            });
            this.updateTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      fetchTeamMembers() {
        return new Promise(resolve => {
          this.teamData = [];
          let name = this.teamName;
          this.$axios.get('/api/getTeamMembers', {params: {name}})
            .then(async (response) => {
              console.log(response.data);
              this.teamMembers = response.data;
              for (var i = 0; i < this.teamMembers.length; i++) {
                let member = {};
                member.name = this.teamMembers[i].username;
                member.email = this.teamMembers[i].email;
                await this.getMemberRanking(member, member.email);
                this.teamData.push(member);
              }
            }).catch((error) => {
            this.handleError(error);
          }).finally(() => resolve(true))
        })
      },
      getMemberRanking(member, email) {
        return new Promise(resolve => {
          this.updateTable();
          let ranking;
          this.$axios.get('/api/getRankingPlace', {params: {email}})
            .then((response) => {
              ranking = response.data;
              member.ranking = ranking;
            }).catch((error) => {
            this.handleError(error);
          }).finally(() => resolve(true))
        })
      },
      fetchTeamInvites() {
        return new Promise(resolve => {
          let token;
          if (localStorage.getItem('userToken')) {
            token = JSON.parse(localStorage.getItem('userToken')).token;
          } else {
            return;
          }
          this.$axios.get('/api/getMyTeamInvites', {params: {token}})
            .then((response) => {
              this.teamInvites = response.data;
              console.log(this.teamInvites);
            }).catch((error) => {
            this.handleError(error);
          }).finally(() => resolve(true))
        })
      },
      joinTeam(teamInvite) {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        params.teamID = teamInvite.team.id;
        this.$axios.put('/api/joinTeam', null, {params})
          .then((response) => {
            console.log(response.data);
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Du bist dem Team " + teamInvite.team.name + " erfolgreich beigetreten!",
              title: "Teambeitrittsanfrage",
              color: "blue"
            });
            this.updateTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      deleteTeamInvite(teamInvite) {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        params.teamInviteID = teamInvite.id;
        this.$axios.delete('/api/deleteTeamInvite', {params})
          .then((response) => {
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Du hast die Anfrage von Team " + teamInvite.team.name + " gelöscht!",
              title: "Teambeitrittsanfrage",
              color: "blue"
            });
            this.updateTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      sendTeamInvite() {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        params.invitedUserEmail = this.inviteMail;
        this.$axios.post('/api/sendTeamInvite', null, {params})
          .then((response) => {
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {
              message: "Du hast " + params.invitedUserEmail + " eingeladen!",
              title: "Einladung ins Team",
              color: "blue"
            });
          }).catch((error) => {
          this.handleError(error);
        })
      },
      setTeamStatus() {
        let params = {};
        if (localStorage.getItem('userToken')) {
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
        } else {
          return;
        }
        params.teamStatus = this.teamStatus;
        this.$axios.put('/api/setTeamStatus', null, {params})
          .then((response) => {
            this.updateTeamData();
          }).catch((error) => {
          this.handleError(error);
        });
        this.updateStatus();
      },
      handleError(error) {
        // Error
        let msg;
        let title;
        if (error.response) {
          // The request was made and the server responded with a status code
          title = "Problem with response!";
          msg = error.response;
        } else if (error.request) {
          // The request was made but no response was received
          title = "Problem with request!";
          msg = "Error occured due to wrong server request!";
          console.log(error.request);
        } else {
          // Something happened in setting up the request that triggered an Error
          title = "Error";
          msg = error.message;
          console.log('Error', error.message);
        }
        console.log(error.config);
        this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: msg, title: title,});
      }
    }
  }
</script>
