<template>
  <div>
<!--    <div :is="stationComponent" @q-tb="scrollToBottomState" :stationObject="tempStation">STATION</div>-->
<!--    <div v-show="!stationComponent">-->
      <form>
        <div class="q-pa-md q-gutter-y-md">
          <p class="text-h5">{{ isNewCache ? "Neuen Cache erstellen" : "Cache bearbeiten"}}</p>
          <q-input class="col" dense stack-label filled v-model="tempCache.name" label="Name" @change="cacheToStore"/>
          <q-input
            v-model="tempCache.description"
            dense
            stack-label
            filled
            autogrow
            type="textarea"
            label="Beschreibung"
            @change="cacheToStore"
          />
          <q-input class="col" dense stack-label filled v-model="tempCache.rankingPoints" label="Punktewert"
                   @change="cacheToStore"/>
          <q-input
            disable
            v-model="tempCache.reward"
            dense
            stack-label
            filled
            autogrow
            type="textarea"
            label="Belohnung"
            @change="cacheToStore"
          />
          <p class="text-h6">Stationen</p>
          <q-list bordered separator class="rounded-borders">

            <q-item v-for="(station, index) in cache.stationen" :key="index">
              <q-item-section avatar>
                <q-avatar color="primary" text-color="white">
                  {{ index + 1 }}
                </q-avatar>
              </q-item-section>

              <q-item-section top>
                <q-item-label lines="1">
                  <span class="text-grey-8">ID: {{ station.id ? station.id : "keine" }}</span>
                </q-item-label>
                <q-item-label lines="1" class="q-mt-xs text-body2">
                  <span class="cursor-pointer">{{ station.description }}</span>
                </q-item-label>
                <q-item-label caption lines="1">
                  Code: {{ station.code }}
                </q-item-label>
              </q-item-section>

              <q-item-section side>
                <div class="text-grey-8 q-gutter-xs">
                  <q-btn @click="deleteStation(index)" class="" color="" flat dense round icon="delete"/>
                  <q-btn @click="editStation(index)" class="" color="" flat dense round icon="edit"/>
                </div>
              </q-item-section>
            </q-item>

          </q-list>
          <div class="row reverse">
            <q-btn @click="addStation" unelevated color="primary" label="Station hinzufügen" icon-right="add"/>
          </div>
          <div class="row q-mt-xl">
            <q-btn @click="saveCache" class="full-width" color="primary" unelevated stack label="Cache speichern"
                   icon="save_alt"/>
          </div>
        </div>
      </form>
<!--    </div>-->
  </div>
</template>

<script>
  // import station from './StationEdit'
  import {mapGetters} from 'vuex';

  export default {
    name: "Cache",
    data() {
      return {
        // stationComponent: null,
        scrolldown: false,
        isNewCache: this.$route.params.id === undefined,
        tempCache: {},
      }
    },
    // components: {
    //   station
    // },
    beforeCreate: function () {
    },
    created: function () {
      console.log("isNewCache: " + this.isNewCache);
      console.log("fetch Caches from Store");
      this.tempCache = JSON.parse(JSON.stringify(this.cache));
    },
    beforeMount: function () {
    },
    mounted: function () {
      console.log("Scrolldown: " + this.scrolldown)
    },
    updated: function () {
      if (this.scrolldown) {
        console.log("scroll down...");
        window.scrollTo(0, document.body.scrollHeight);
        this.scrolldown = false
      }
      //this.SET_CACHE(this.tempCache);
      //this.scrollToBottom();
    },
    methods: {
      // ...mapMutations([
      //   'cacheCollector/SET_CACHE',
      //   'cacheCollector/ADD_STATION',
      //   'cacheCollector/REMOVE_STATION',
      //   'cacheCollector/RESET_NEW_CACHE',
      //   'cacheCollector/LOAD_REMOTE_CACHE'
      // ]),
      // swapComponent: function (component) {
      //   this.stationComponent = component;
      // },
      cacheToStore() {
        // push tempCache to Store
        console.log("set Cache");
        this.$store.commit('cacheCollector/SET_CACHE', JSON.parse(JSON.stringify(this.tempCache)));
        // this.SET_CACHE(JSON.parse(JSON.stringify(this.tempCache)));
      },
      addStation() {
        this.$router.push({ path: '/station' });
        //this.swapComponent(station);
        // create Station and add it to array tempCache.stationen
      },
      editStation(index) {
        console.log("editStation("+index+")");
        const station = this.cache.stationen[index];
        console.log(station)
        if (station.hasOwnProperty('id') ) {
          //this.$router.push({ path: '/station/'+station.id});
        } else {
          // TODO Stationen bearbeitbar machen bevor sie abgeschickt werden. Am besten Station Objekt als Übergabe Parameter bei Router
          this.$store.commit('cacheCollector/SET_TEMPSTATION', station);
          this.$router.push({ path: `/station-l/${index}` }); // add parameter
        }
      },
      deleteStation(index) {
        // TODO wenn Station id hat, mit Backend abgleichen
        this.$store.commit('cacheCollector/REMOVE_STATION', index);
      },
      saveCache() {
        // commit to store, send to api, if success -> reset store
        if (this.isNewCache) {
          console.log(this.cache);
          console.log(JSON.stringify(this.cache));
          this.$axios.post('http://localhost:8080/api/createCache', this.cache)
            .then((response) => {
              console.log("POST api/createCache: " + response.statusText);
              this.$store.commit('cacheCollector/RESET_NEW_CACHE');
              this.$router.push({ path: '/overview' });
            })
            .catch((error) => {
            });
          } else {
          // TODO update existing Cache
        }
        },
    },
    computed: {
      ...mapGetters({
        cache: 'cacheCollector/GET_CACHE'
      }),
      // computedCache: {
      //   set(value) {
      //     console.log("set cache")
      //   },
      //   get() {
      //     console.log("get cache");
      //     return this.$store.getters.cacheCollector.GET_CACHE
      //   }
      // }
    }
  }
</script>

<style scoped>

</style>
