<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 || isRefreshing" class="app-fade-in">
      <v-layout row wrap v-if="!hasUser">
        <v-flex xs12>
          <p><b>OBS! Logga in för att kunna filtrera listan</b></p>
        </v-flex>
      </v-layout>
      <v-layout row wrap>
        <v-flex xs12>
          <v-text-field
              v-model="origin"
              label="Startpunkt"
              placeholder="Address/geokoordinat"
          >
            <v-tooltip top slot="append-outer">
              <v-icon slot="activator" v-on:click="fetchAddress()">mdi-crosshairs-gps</v-icon>
              <span>Hämta nuvarande position</span>
            </v-tooltip>
            <v-tooltip top slot="prepend" v-if="hasUser">
              <v-icon slot="activator" :disabled="!origin" v-on:click="saveOrigin(origin)">mdi-bookmark-plus-outline</v-icon>
              <span>Spara startpunkt</span>
            </v-tooltip>
          </v-text-field>
        </v-flex>
      </v-layout>
      <v-layout row wrap>
        <v-flex>
          <v-btn-toggle v-if="$vuetify.breakpoint.smAndUp" v-model="range" mandatory @change="changeRange">
            <v-btn flat v-for="r in ranges" :key="r.value" :value="r.value">{{r.name}}</v-btn>
          </v-btn-toggle>
          <v-select outline v-if="$vuetify.breakpoint.xsOnly" v-model="range" @change="changeRange" :items="ranges" item-text="name" item-value="value"></v-select>
        </v-flex>
      </v-layout>
      <v-layout row wrap v-for="event in events" :key="event.id">
        <v-flex xs12>
          <Event :event="event" :has-user="hasUser" :toggleIgnore="toggleIgnore" />
        </v-flex>
      </v-layout>
    </v-container>
    <v-snackbar
        v-model="snackbar"
        :color="snackColor"
        :timeout="5000"
    >
      {{ snackText }}
    </v-snackbar>
  </div>
</template>

<script>
  import {
    findEvents,
    findEventsAndOrigins,
    fetchAddress,
    toggleIgnoreBand,
    toggleIgnoreDanceHall,
    toggleIgnoreCity,
    toggleIgnoreMunicipality,
    toggleIgnoreState,
    saveOrigin,
    removeOrigin
  } from "~/utils/graph-client";

  import auth from "~/utils/auth";

  import Event from "./Event";

  export default {
    components: {
      Event
    },
    data() {
      return {
        status: "loading",
        origin: undefined,
        origins: [],
        submitInfo: "",
        submitError: "",
        user: undefined,
        snackbar: false,
        snackColor: "success",
        snackText: "",
        range: "ONE_WEEK",
        ranges: [
          {name: "1 vecka", value: "ONE_WEEK"},
          {name: "2 veckor", value: "TWO_WEEKS"},
          {name: "1 månad", value: "ONE_MONTH"},
          {name: "1 kvartal", value: "ONE_QUARTER"},
          {name: "1 år", value: "ONE_YEAR"}
        ]
      };
    },
    computed: {
      isLoading() {
        return this.status === "loading";
      },
      isReady() {
        return this.status === "ready";
      },
      isSubmitting() {
        return this.status === "submitting";
      },
      isSubmitted() {
        return this.status === "submitted";
      },
      isRefreshing() {
        return this.status === "refreshing";
      },
      hasUser() {
        return this.user !== undefined && this.user !== null;
      }
    },
    mounted() {
      this.$store.commit('setTitle', 'Evenemang');
      const {range} = this.$route.query;
      this.range = range || "ONE_WEEK";
      this.fetchUser();
      this.fetchEvents();
    },
    watch: {
      "$route.query"() {
        const {range} = this.$route.query;
        this.range = range;
        this.fetchUser();
        this.fetchEvents();
      }
    },
    methods: {
      fetchEvents (status) {
        this.status = status || "loading";
        const origins = this.origins;
        if (this.origin) {
          origins.push(this.origin);
        }
        const variables = {range: this.range, origins: origins.length > 0 ? origins : null};
        if (this.hasUser) {
          findEventsAndOrigins(variables)
              .then(this.eventsFetched)
              .catch(this.eventsFailed);
        } else {
          findEvents(variables)
              .then(this.eventsFetched)
              .catch(this.eventsFailed);
        }
      },
      eventsFetched(response) {
        if (response.errors) {
          throw new Error("Fetch failed");
        }
        this.events = response.data.events;
        this.origins = response.data.origins || [];
        this.status = "ready";
      },
      eventsFailed() {
        this.status = "load-failed";
      },
      fetchUser() {
        this.user = auth.getUserInfo();
      },
      toggleIgnore(type, name) {
        switch (type) {
          case 'band':
            toggleIgnoreBand({name: name})
                .then(this.toggleIgnoreSuccess(name))
                .catch(this.toggleIgnoreFailed);
            break;
          case 'danceHall':
            toggleIgnoreDanceHall({name: name})
                .then(this.toggleIgnoreSuccess(name))
                .catch(this.toggleIgnoreFailed);
            break;
          case 'city':
            toggleIgnoreCity({name: name})
                .then(this.toggleIgnoreSuccess(name))
                .catch(this.toggleIgnoreFailed);
            break;
          case 'municipality':
            toggleIgnoreMunicipality({name: name})
                .then(this.toggleIgnoreSuccess(name))
                .catch(this.toggleIgnoreFailed);
            break;
          case 'state':
            toggleIgnoreState({name: name})
                .then(this.toggleIgnoreSuccess(name))
                .catch(this.toggleIgnoreFailed);
            break;
        }
      },
      toggleIgnoreSuccess(name) {
        return () => {
          this.fetchEvents('refreshing');
          this.snackColor = 'success';
          this.snackText = `${name} har dolts`;
          this.snackbar = true;
        }
      },
      toggleIgnoreFailed(name) {
        return () => {
          this.snackColor = 'error';
          this.snackText = `${name} kunde inte döljas`;
          this.snackbar = true;
        }
      },
      saveOrigin(origin) {
        saveOrigin({origin: origin})
            .then(saved => {
              if (saved) {
                this.origins = [];
                this.origin = "";
                this.fetchEvents('refreshing');
              } else {
                this.snackColor = 'error';
                this.snackText = `${origin} kunde inte sparas`;
                this.snackbar = true;
              }
            })
            .catch(() => {
              this.snackColor = 'error';
              this.snackText = `${origin} kunde inte sparas`;
              this.snackbar = true;
            })
      },
      changeRange(range) {
        this.$router.push(`/?range=${range}`);
      },
      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;
                this.fetchEvents('refreshing');
              })
          })
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .left {
    padding: 1.5rem 1rem;

    > * {
      margin-bottom: 1.5rem;
    }

    hr {
      border: 0;
      border-top: 1px solid #eaeaea;
    }
  }

  .left,
  .right {
    height: 100vh;
    overflow: scroll;
    overflow-x: hidden;
    position: relative;
  }

  @media screen and(max-width: 1200px) {
    .left {
      width: 40vw;
    }
    .right {
      width: 60vw;
    }
  }

  @media screen and(max-width: 1024px) {
    .left {
      width: 50vw;
    }
    .right {
      width: 50vw;
    }
  }

  @media screen and(min-width: 1200px) {
    .left {
      width: 35vw;
    }
    .right {
      width: 65vw;
    }
  }
</style>
