<template>
  <div>
    <app-loader :show="isLoading" />
    <app-loader v-if="isSubmitting" overlay>
      <p>
        {{submitInfo}}
      </p>
    </app-loader>
    <v-container fluid grid-list-md v-if="isReady || isSubmitting || isSubmitted" class="app-fade-in">
      <v-layout row wrap>
        <v-flex xs12>
          <v-text-field
              v-model="origin"
              label="Startpunkt"
              placeholder="Address/geokoordinat"
          >
            <v-tooltip top slot="append-outer">
              <template v-slot:activator="{ on }">
                <v-icon v-on="on" v-on:click="fetchAddress()">mdi-crosshairs-gps</v-icon>
              </template>
              <span>Hämta nuvarande position</span>
            </v-tooltip>
            <v-tooltip top slot="prepend">
              <template v-slot:activator="{ on }">
                <v-icon v-on="on" :disabled="!origin" v-on:click="saveOrigin(origin)">mdi-bookmark-plus-outline</v-icon>
              </template>
              <span>Spara startpunkt</span>
            </v-tooltip>
          </v-text-field>
        </v-flex>
      </v-layout>
      <v-layout row wrap v-for="origin in origins" :key="origin">
        <v-flex xs12>
          <v-icon v-on:click="removeOrigin(origin)">mdi-delete-outline</v-icon>
          <span>{{origin}}</span>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>

<script>
  import {
    findOrigins,
    saveOrigin,
    removeOrigin,
    fetchAddress,
  } from "~/utils/graph-client";

  export default {
    data() {
      return {
        status: "loading",
        origin: undefined,
        submitInfo: "",
        snackbar: false,
        snackColor: "success",
        snackText: "",
      };
    },
    computed: {
      isLoading() {
        return this.status === "loading";
      },
      isReady() {
        return this.status === "ready";
      },
      isSubmitting() {
        return this.status === "submitting";
      },
      isSubmitted() {
        return this.status === "submitted";
      },
    },
    mounted() {
      this.$store.commit('setTitle', 'Startpunkter');
      this.fetchOrigins();
    },
    methods: {
      fetchOrigins() {
        this.status = "loading";
        findOrigins()
            .then(this.originsFetched)
            .catch(this.originsFailed);
      },
      originsFetched(response) {
        if (response.errors) {
          throw new Error("Fetch failed");
        }
        this.origins = response.data.origins;
        this.status = "ready";
      },
      originsFailed() {
        this.status = "load-failed";
      },
      saveOrigin(origin) {
        this.submitInfo = 'Sparar startpunkt';
        this.status = 'submitting';
        saveOrigin({origin: origin})
            .then(saved => {
              this.status = 'submitted';
              if (saved) {
                this.origins = [];
                this.origin = "";
                this.fetchOrigins();
              } else {
                this.snackColor = 'error';
                this.snackText = `${origin} kunde inte sparas`;
                this.snackbar = true;
              }
            })
            .catch(() => {
              this.status = 'submit-failed';
              this.snackColor = 'error';
              this.snackText = `${origin} kunde inte sparas`;
              this.snackbar = true;
            })
      },
      removeOrigin(origin) {
        this.submitInfo = 'Tar bort startpunkt';
        this.status = 'submitting';
        removeOrigin({origin: origin})
            .then(removed => {
              this.status = 'submitted';
              if (removed) {
                this.origins = [];
                this.fetchOrigins();
              } else {
                this.snackColor = 'error';
                this.snackText = `${origin} kunde inte tas bort`;
                this.snackbar = true;
              }
            })
            .catch(() => {
              this.status = 'submit-failed';
              this.snackColor = 'error';
              this.snackText = `${origin} kunde inte tas bort`;
              this.snackbar = true;
            })
      },
      fetchAddress() {
        if (window.navigator) {
          this.submitInfo = 'Hämtar aktuell position';
          this.status = 'submitting';
          window.navigator.geolocation.getCurrentPosition(pos => {
            fetchAddress({latlng: pos.coords.latitude + "," + pos.coords.longitude})
                .then(response => {
                  this.status = 'submitted';
                  this.origin = response.data.address;
                })
          })
        }
      },
    }
  }
</script>
