<template>
  <div class="app">
    <div class="fluid-container">
      <div class="d-flex justify-content-between border-bottom">
        <h1 class="py-2 pr-2">Pinboard Groupings</h1>
  
        <div class="tags-form py-2 pl-2">      
          <form @submit.prevent="saveNewGrouping" class="form-inline" v-if="apiKey">
            <div class="form-group">
              <label class="sr-only" for="tags">Tags</label>
              <input type="text" class="form-control p-0 h-auto" id="tags"
                      v-model="newGrouping.tags"
                      placeholder="new grouping tags">
            </div>
            <button type="submit" class="btn btn-link p-0 pl-2">add grouping</button>
          </form>
        </div>

        <div class="api-key-form py-2 pl-2">      
          <form @submit.prevent="saveApiKey" class="form-inline">
            <div class="form-group" v-if="!apiKey">
              <label class="sr-only" for="apiKey">Pinboard API Key</label>
              <input type="text" class="form-control p-0 h-auto" id="apiKey"
                      v-model="form.apiKey"
                      placeholder="Enter Pinboard API key">
            </div>
            <div v-else>
              {{ apiKey }}
            </div>
            <button type="submit" class="btn btn-link p-0 pl-2" v-if="!apiKey">save</button>
            <button type="button" class="btn btn-link p-0 pl-2" @click.prevent="editApiKey" v-else>edit</button>
          </form>
        </div>
      </div>

      <div class="alert alert-danger" role="alert" v-if="error">
        {{ error }}
      </div>

      <div class="my-2" v-if="apiKey && groupings.length > 0">
        <button type="button" class="btn btn-link p-0"
          @click="refreshGroupings">
          refresh groupings
        </button>
      </div>

      <div class="groupings card-columns" v-if="apiKey">
        <div class="grouping card" v-for="(grouping, index) in groupings" v-bind:key="grouping.tags">
          <div class="card-body">
            <h5 class="card-title d-flex justify-content-between">
              <span>{{ grouping.tags }}</span>
              <button type="button"
                class="btn btn-link p-0"
                :dataIdx="index"
                @click="deleteGrouping(index)">
                delete
              </button>
            </h5>
            <p class="card-text" v-if="grouping.loading">
              loading...
            </p>
            <p class="card-text m-0" v-else v-for="pin in grouping.pins" v-bind:key="pin.hash">
              <a target="_blank" :href="pin.href">{{ pin.description }}</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      apiKey: null,
      groupings: [],
      form: {
        apiKey: null
      },
      newGrouping: {
        tags: ""
      },
      error: null
    }
  },
  methods: {
    deleteGrouping(index) {
      this.groupings.splice(index, 1);
      this.persistGroupings();
    },
    refreshGroupings(event) {
      var promises = [];
      for(var key in this.groupings) {
        var grouping = this.groupings[key];
        grouping.loading = true;
        grouping.pins = [];

        promises.push(this.getPinsForGroup(key));
      }
      
      axios.all(promises).finally(() => {
        this.persistGroupings();
      });
    },
    getPinsForGroup(index) {
      var url = "https://api.pinboard.in/v1/posts/all?format=json&results=30";
      url += "&auth_token=" + this.apiKey;
      url += "&tag=" + this.groupings[index].tags;
      
      var promise = axios.get(url);
      promise.then(response => {
          this.groupings[index].pins = response.data;
          this.groupings[index].loading = false;
        })
        .catch(error => {
          this.error = error;
        });
      return promise;
    },
    saveNewGrouping(event) {
      if (this.newGrouping.tags === "") {
        return;
      }

      this.groupings.push({
        tags: this.newGrouping.tags,
        pins: [],
        loading: true
      });
      this.newGrouping = { tags: [] };
      this.getPinsForGroup(this.groupings.length - 1)
        .finally(() => {
          this.persistGroupings();
        });
    },
    saveApiKey(event) {
      var data = {
        apiKey: this.form.apiKey,
        groupings: this.apiKey !== this.form.apiKey ? [] : this.groupings
      };
      chrome.storage.local.set(data, () => {
        this.apiKey = data.apiKey;
        this.groupings = data.groupings;
      });
    },
    persistGroupings() {
      var data = { groupings: this.groupings };
      chrome.storage.local.set(data, () => {});
    },
    editApiKey(event) {
      this.form.apiKey = this.apiKey;
      this.apiKey = null;
    }
  },
  mounted() {
    chrome.storage.local.get(['apiKey','groupings'], result => {
      this.apiKey = result.apiKey;
      this.groupings = result.groupings;
    });
  }
}
</script>

<style lang="scss" scoped>
@import 'node_modules/bootstrap/scss/bootstrap';

.app {
  font-size: 1rem;
}

h1 {
  font-size: 1rem;
}
.api-key-form *, .tags-form * {
  font-size: 0.8rem;
}
.api-key-form input.form-control {
  width: 17rem;
}

</style>
