<template>
  <q-page class="column">
    <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="list" label="Liste" icon="list"/>
        <q-tab name="map" label="Karte" icon="map"/>
      </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="list" class=" fit">
          <q-spinner-oval
            v-if="!render"
            class="absolute-center"
            color="primary"
            size="10em"
          />
          <q-list v-if="render">
            <q-card class="q-mb-md" v-for="cache in caches" :key="cache.id">
              <q-expansion-item
                class=""
                expand-separator
                icon="location_on"
                :header-class="'text-'+(getColorClass(cache) === 'primary' ? 'black' : getColorClass(cache))"
                :label="cache.name"
                :caption="cache.rankingPoints+' Punkte, '+cache.stationen.length+' Stationen'"
              >
                <q-item>
                  <q-item-section top avatar class="self-center">
                    <!--<q-icon rounded color="cyan-14" name="location_on" size="3rem"/>-->
                  </q-item-section>
                  <q-item-section>
                    <q-item-label caption v-html="cache.description"></q-item-label>
                  </q-item-section>

                  <q-item-section side top class="self-center">
                  </q-item-section>
                </q-item>
                <q-item class="q-pr-sm reverse q-gutter-x-sm">
                  <q-btn v-if="(getCacheAccesDefinition(cache) === -1)" @click="startCache(cache.id)" unelevated
                         :color="getColorClass(cache)" stack icon="arrow_forward"
                         label="Starten" size="xs"/>
                  <q-btn v-if="(getCacheAccesDefinition(cache) === 0)" @click="continueCache(cache.id)" unelevated
                         :color="getColorClass(cache)" stack icon="arrow_forward"
                         label="Fortsetzen" size="xs"/>
                  <q-btn v-if="(getCacheAccesDefinition(cache) === 1)" @click="goToReward(cache.id)" unelevated
                         :color="getColorClass(cache)" stack icon="arrow_forward"
                         label="Belohnung" size="xs"/>
                  <q-btn v-if="hasAdminState" @click="confirmDelete(cache.id)" unelevated color="negative" stack
                         icon="delete" size="xs"/>
                  <q-btn disable v-if="hasAdminState" @click="editCache(cache.id)" unelevated color="primary" stack
                         icon="edit" size="xs"/>
                  <q-btn v-if="hasAdminState" @click="generateQrCodes(cache.id)" unelevated color="primary" stack
                         icon="image" label="QRCodes" size="xs"/>
                </q-item>
              </q-expansion-item>
            </q-card>
          <div v-if="hasAdminState" class="row">
            <q-btn @click="addCache" unelevated color="primary" stack icon="add" label="Neuer Cache"
                   class="full-width"/>
          </div>
          </q-list>
        </q-tab-panel>


        <q-tab-panel name="map" class="q-pa-none fit">
          <!--<div class="full-width full-height absolute-full" style="background: url('statics/osm_mock.png'); background-size: cover">-->
          <!--</div>-->
          <q-img
            src="https://www.buga2019.de/we-bilder/3.Gartenausstellung/Gelaendeplan/190320_Gelaendeplan-quadratisch.jpg"
            transition="fade" class="absolute-full">
            <template v-slot:loading>
              <q-spinner-puff color="cyan-14" size="4em"/>
            </template>
          </q-img>
        </q-tab-panel>

      </q-tab-panels>

    </div>
  </q-page>

</template>

<style>
  /*
    .my-list-card-item
      padding-left: 8px
  */
</style>
<script>
  export default {
    data() {
      return {
        tab: 'list',
        caches: [],
        stations: [],
        pois: [],
        render: false
      }
    },
    mounted: function () {
    },
    computed: {
      hasAdminState() {
        return this.$store.getters['auth/GET_ADMINSTATE'];
      }
    },
    beforeMount() {
    },

    async created() {
      console.log("created(): " + this.caches);
      // this.$store.commit('auth/SET_AUTHENTICATED');
      // this.$store.commit('auth/SET_USER');
      await this.fetchAllCaches();
      this.render = await this.fetchMyCaches();
    },
    methods: {
      getColorClass(cache) {
        switch (this.getCacheAccesDefinition(cache)) {
          case -1:
            return "primary"
          case 0:
            return "amber"
          case 1:
            return "green"
        }
      },
      getCacheAccesDefinition(cache) {
        // console.log("getCacheAccessDefinition")
        // console.log(cache.hasOwnProperty('cacheAccesDefinition') ? cache.cacheAccesDefinition : -1)
        // can be -1 = no accessdefinition, 0 = started or 1 = finished
        return cache.hasOwnProperty('cacheAccesDefinition') ? cache.cacheAccesDefinition : -1;
      },

      fetchAllCaches() {
        return new Promise(resolve => {
          this.$axios.get('/api/allCaches')
            .then((response) => {
              this.caches = response.data;
              //this.fetchMyCaches();
              for (let cache in this.caches) {

                this.stations[cache] = (this.caches[cache].stationen[0]);
                const poiItem = {
                  Name: this.caches[cache].name,
                  CategoryID: 3,
                  Latitude: this.stations[cache].lattitude,
                  Longitude: this.stations[cache].longitude
                };
                this.pois.push(poiItem);
              }
              this.initMap();
              resolve(true);
            }).catch((error) => {
            let message;
            let header = "Fehler: ";
            if (error.response) {
              console.log("ERROR RESPONSE");
              // The request was made and the server responded with a status code
              // that falls out of the range of 2xx
              message = error.response.data.error;
              header += error.response.status;
            } else if (error.request) {
              // The request was made but no response was received
              // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
              // http.ClientRequest in node.js
              message = "Anfrage fehlgeschlagen.";
            } else {
              // Something happened in setting up the request that triggered an Error
              console.log('Error', error.message);
              message = error.message;
            }
            console.log(error.config);
            this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: message, title: header,});
            resolve(true);
          })
        })
      },

      fetchMyCaches() {
        return new Promise(resolve => {
          console.log("fetchMyCaches...");
          if (this.$store.state.auth.isAuthenticated && localStorage.getItem('userToken')) {
            const token = JSON.parse(localStorage.getItem('userToken')).token;
            this.$axios.get('/api/getMyCaches', {params: {token}})
              .then((response) => {
                console.log("process data...")
                console.log(response.data)
                for (let item of response.data) {
                  this.caches.forEach(cache => {
                    if (cache.id === item.cache.id) {
                      cache.cacheAccesDefinition = item.cacheAccesDefinition.id;
                      console.log("found accessdefinition: id: " + cache.id + " ad: " + cache.cacheAccesDefinition);

                    }
                  })
                }
                console.log(this.caches);
                console.log("data processed.")
              }).finally(() => resolve(true))
          } else {
            resolve(true);
          }
        })
      },

      confirmDelete(cacheID) {
        this.$q.dialog({
          title: 'Löschen...',
          message: 'Willst du diesen Cache wirklich löschen?',
          persistent: true,
          cancel: true,
        }).onOk(() => {
          console.log('>>>> OK');
          this.deleteCache(cacheID)
        }).onCancel(() => {
          console.log('>>>> Cancel')
        }).onDismiss(() => {
        })
      },

      addCache() {
        this.$router.push({path: `/cache`})
      },
      editCache() {
      },
      initMap() {
        console.log("Signalwort: " + this.pois);
        //   this.$axios.post('http://seserver.se.hs-heilbronn.de:3000/api/map', {
        //     body: this.pois
        //   }).then((response)=>{
        //     console.log(response)
        //   })
        // },
        this.$axios.get('http://www.se.hs-heilbronn.de:3000/api/map/lon=9&lat=49', {
          body: this.pois
        }).then((response) => {
          console.log(response)
        })
      },
      deleteCache(id) {
        console.log('delete cache: ' + id);
        axios.get('/api/deleteCache', {params: {cacheID: id}})
          .then((response) => {
            this.fetchAllCaches()
          }).catch((error) => {
          let message;
          let header = "Fehler: ";
          if (error.response) {
            console.log("ERROR RESPONSE");
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            message = error.response.data.error;
            header += error.response.status;
          } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
            // http.ClientRequest in node.js
            message = "Anfrage fehlgeschlagen.";
          } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', error.message);
            message = error.message;
          }
          console.log(error.config);
          this.$store.commit('dialog/NEW_MESSAGE_DIALOG', {message: message, title: header,});
        })
      },
      startCache(cacheID) {
        console.log("startCache()");
        this.$store.state.currentCache.cache = this.caches.find(cache => cache.id === Number(cacheID));
        console.log(this.$store.state.currentCache.cache);
        this.$store.state.currentCache.currentCacheID = Number(cacheID);
        this.$router.push({path: `/CacheStart/${cacheID}`})
      },
      continueCache(cacheID) {
        console.log("cacheID");
        console.log(cacheID);
        let currentStationID;
        if (localStorage.getItem('userToken')) {
          let params = {cacheID: cacheID};
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
          this.$axios.get('/api/getCurrentStation', {params})
            .then((response) => {
              console.log(response.data);
              currentStationID = response.data.aktuelleStation.id;
              this.$router.push({path: `/station/${cacheID}/${currentStationID}`});
            })
            .catch((error) => {
            });
        }
      },
      goToReward(cacheID) {
        console.log("cacheID");
        console.log(cacheID);
        let currentStationID;
        if (localStorage.getItem('userToken')) {
          let params = {cacheID: cacheID};
          params.token = JSON.parse(localStorage.getItem('userToken')).token;
          this.$axios.get('/api/getCurrentStation', {params})
            .then((response) => {
              console.log(response.data);
              currentStationID = response.data.aktuelleStation.id;
              this.$router.push({path: `/CacheEnd/${params.cacheID}`});
            })
            .catch((error) => {
            });
        }
      },

      generateQrCodes(cacheID) {
        this.$router.push({path: `/generator/${cacheID}`})
      }
    }
  }
</script>
