<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 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">
          <p class="text-h5"> Persönliche Daten </p>
          <q-table
            :data="data"
            :columns="columns"
            row-key="name"
            hide-header
            hide-bottom
            table-class="my-custom"
          />
        </q-tab-panel>
        <q-tab-panel name="teams">
          <div class="q-pa-md" align="center">
            <q-btn-dropdown color="primary" :label="dropDownSelectedItem" size="20px">
              <q-list>
                <q-item :clickable="boolAlreadyInTeam" v-close-popup @click="dropDownSelectItem('team')"
                        :disabled="!boolAlreadyInTeam">
                  <q-item-section>
                    <q-item-label v-html="teamName"></q-item-label>
                  </q-item-section>
                </q-item>

                <q-item clickable v-close-popup @click="dropDownSelectItem('Offene Teameinladungen')">
                  <q-item-section avatar>
                    <q-avatar icon="group_add" color="primary" text-color="white"/>
                  </q-item-section>
                  <q-item-section>
                    <q-item-label>Offene Teameinladungen</q-item-label>
                  </q-item-section>
                </q-item>

                <q-item :clickable="!boolAlreadyInTeam" v-close-popup :disabled="boolAlreadyInTeam"
                        @click="dropDownSelectItem('Neues Team erstellen')">
                  <q-item-section avatar>
                    <q-avatar icon="add" color="primary" text-color="white"/>
                  </q-item-section>
                  <q-item-section>
                    <q-item-label v-show="!boolAlreadyInTeam">Neues Team erstellen</q-item-label>
                    <q-item-label v-show="boolAlreadyInTeam">Neues Team erstellen<br/>(Team verlassen um Option zu
                      nutzen)
                    </q-item-label>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-btn-dropdown>
          </div>
          <div v-show="boolMyTeam">
            <p class="text-h5"> Teammitglieder </p>
            <q-table
              :data="teamData"
              :columns="teamColumns"
              row-key="name"
              table-class="my-custom"
              hide-bottom
              :pagination.sync="pagination"
            />
            <br/>
            <p class="text-h5"> Einladungen </p>
            <q-input lazy-rules outlined filled stack-label v-model="inviteMail"
                     type="text" label="Email des Nutzers"
                     :rules="[val=>validateEmail(val)||'Bitte Email verwenden']"/>
            <div align="center">
              <q-btn label="Einladung versenden"
                     @click="sendTeamInvite()"
                     :disabled="!teamInviteChecked"
                     color="primary"
                     type="submit"/>
            </div>
            <br/>
            <p class="text-h5"> Teamstatus </p>
            <p>{{currentTeamStatus}}</p>
            <q-input lazy-rules outlined filled stack-label v-model="teamStatus"
                     type="text" label="Neuer Teamstatus"
                     :rules="[val=>val.length<=160||'Status zu lang!']"/>
            <div align="center">
              <q-btn label="Teamstatus aktualisieren"
                     :disabled="!teamStatusChecked"
                     @click="setTeamStatus()"
                     color="primary"
                     type="submit"/>
            </div>
            <br/>
            <q-input lazy-rules outlined filled stack-label v-model="leaveTeamCheck"
                     type="text" label="BESTÄTIGEN eingeben um das Team zu verlassen"
                     :rules="[val=>val==='BESTÄTIGEN'||'Schreibweise beachten']"/>
            <div align="center">
              <q-btn label="Team verlassen"
                     :disabled="!leaveConfirmed"
                     @click="leaveTeam()"
                     color="negative"
                     type="submit"/>
            </div>
          </div>
          <div v-show="boolInvites">
            <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 @click="joinTeam(teamInvite)" unelevated color="positive" stack icon="arrow_forward"
                           label="Anfrage annehmen" size="sm"/>
                    <q-btn @click="deleteTeamInvite(teamInvite)" unelevated color="negative" stack icon="delete"
                           label="Anfrage ablehnen" size="sm"/>
                  </q-item>
                </q-expansion-item>
              </q-card>
            </q-list>
          </div>
          <div v-show="boolCreateTeam">
            <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>
        </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,
        dropDownSelectedItem: null,
        boolMyTeam: true,
        boolInvites: false,
        boolCreateTeam: false,
        newTeamName: "",
        leaveTeamCheck: "",
        teamMembers: [],
        teamInvites: [],
        columns: [
          {
            name: 'desc',
            required: true,
            align: 'left',
            field: row => row.name,
            format: val => `${val}`,
          },
          {
            name: 'userData',
            required: true,
            align: 'left',
            field: 'userData',
          }
        ],
        data: [
          {
            name: 'Benutzername',
            userData: this.userName,
          },
          {
            name: 'E-Mail',
            userData: this.email,
          },
          {
            name: 'Rang',
            userData: this.userRanking,
          },
          {
            name: 'Team',
            userData: this.teamName,
          },
          {
            name: 'Team-Rang',
            userData: this.teamRanking,
          },
        ],
        teamColumns: [
          {
            name: 'desc',
            label: 'Benutzername',
            required: true,
            align: 'left',
            field: row => row.name,
            format: val => `${val}`,
          },
          {
            name: 'email',
            label: 'Email',
            required: true,
            align: 'left',
            field: 'email',
          },
          {
            name: 'ranking',
            label: 'Rangliste (Solo)',
            required: true,
            align: 'left',
            field: 'ranking',
            sortable: true,
          }
        ],
        teamData: [],
        pagination: {
          sortBy: 'ranking',
          descending: false,
          page: 1,
          rowsPerPage: 10
          // rowsNumber: xx if getting data from a server
        },
      }
    },
    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.data[0].userData = this.userName;
      this.email = JSON.parse(localStorage.getItem('userMail'));
      this.data[1].userData = this.email;
      this.getPersonalRanking();
      this.getTeamData();
      this.fetchTeamInvites();
    },
    methods: {
      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;
            this.data[2].userData = this.userRanking;
          }).catch((error) => {
          this.handleError(error);
        })
      },
      getTeamData() {
        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 = "-";
              this.dropDownSelectItem('Offene Teameinladungen');
            } else {
              this.boolAlreadyInTeam = true;
              this.teamName = response.data.name;
              this.currentTeamStatus = response.data.teamStatus;
              //this.teamRanking = response.data.teamRanking;
              this.fetchTeamMembers();
            }
            this.data[3].userData = this.teamName;
            this.dropDownSelectedItem = this.teamName;
            this.data[4].userData = this.teamRanking;
            console.log("getTeam: " + response);
          }).catch((error) => {
          this.handleError(error);
        })
      },

      dropDownSelectItem(item) {
        if (item === 'team') {
          this.dropDownSelectedItem = this.teamName;
          this.boolMyTeam = true;
          this.boolInvites = false;
          this.boolCreateTeam = false;
        } else if (item === 'Offene Teameinladungen') {
          this.dropDownSelectedItem = item;
          this.boolMyTeam = false;
          this.boolInvites = true;
          this.boolCreateTeam = false;
        } else {
          this.dropDownSelectedItem = item;
          this.boolMyTeam = false;
          this.boolInvites = false;
          this.boolCreateTeam = 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"
            });
          }).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: "Dus hast das Team " + this.teamName + " verlassen!",
              title: "Team verlassen",
              color: "blue"
            });
            this.getTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      fetchTeamMembers() {
        let name = this.teamName;
        this.$axios.get('/api/getTeamMembers', {params: {name}})
          .then((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;
              this.getMemberRanking(member, member.email);
              this.teamData.push(member);
            }
          }).catch((error) => {
          this.handleError(error);
        })
      },
      getMemberRanking(member, email) {
        let ranking;
        this.$axios.get('/api/getRankingPlace', {params: {email}})
          .then((response) => {
            ranking = response.data;
            member.ranking = ranking;
          }).catch((error) => {
          this.handleError(error);
        });
      },
      fetchTeamInvites() {
        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);
        })
      },
      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.getTeamData();
          }).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.getTeamData();
          }).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.getTeamData();
          }).catch((error) => {
          this.handleError(error);
        })
      },
      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>
