<template>
  <div>
    <ul class="collection with-header">
      <li class="collection-header">
        <h4>Connected accounts</h4>
      </li>
      <li class="collection-item avatar" v-for="account in accounts" :key="account.id">
        <img v-if="account._source.getAvatar(account)" :src="account._source.getAvatar(account)" alt="" class="circle">
        <span class="title">{{ account._source.getDisplayName(account) }}</span>
        <p>{{ account._source.label }}</p>
        <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
      </li>
    </ul>
    <h2>Suggestions</h2>
    <button
      @click="fetch"
      :class="['waves-effect', 'waves-light', {disabled: isLoading}, 'btn-small']" :disabled="isLoading">
      <i class="material-icons left">refresh</i>Fetch data
    </button>
    <div v-if="isLoading" class="progress">
      <div class="indeterminate"></div>
    </div>
  </div>

</template>

<script>
import sources from '@/sources'
export default {
  data () {
    return {
      isLoading: false,
      results: {}
    }
  },
  computed: {
    accounts () {
      return this.$store.getters.sortedAccounts.map((a) => {
        a._source = sources.sources[a.source]
        return a
      })
    }
  },
  methods: {
    async fetch () {
      this.isLoading = true
      this.accounts.forEach((a) => {
        let r = {}
        let promise = a._source.fetch({account: a, store: this.$store, results: r, vue: this})
        this.$set(this.results, a.id, {account: a, promise, results: r})
      })
      const keys = Object.keys(this.results)
      for(let i = 0; i < keys.length; i++){
        await this.results[keys[i]].promise
      }
      this.isLoading = false
    }
  }
}
</script>