<template>
  <div class="md-layout md-aligment-center" style="margin: 4em 0">
    <!-- TOP Navigation-->
    <md-toolbar class="fixed-toolbar" elevation="1">
      <md-button @click="showLeftSidepanel = true" class="md-icon-button">
        <md-icon>menu</md-icon>
      </md-button>
      <nuxt-link class="md-primary md-title" to="/">
        NuxtNews
      </nuxt-link>
      <div class="md-toolbar-section-end">
        <template v-if="isAuthenticated">
          <md-button>
            <md-avatar><img :src="user.avatar" :alt="user.email"></md-avatar>{{ user.email }}
          </md-button>
          <md-button @click="logoutUser">
            Logout
          </md-button>
        </template>

        <template v-else>
          <md-button @click="$router.push('/login')">
            Login
          </md-button>
          <md-button @click="$router.push('/register')">
            Register
          </md-button>
        </template>

        <md-button @click="showSearchDialog=true" class="md-primary">
          Search
        </md-button>

        <md-button @click="showRightSidepanel = true" class="md-accent">
          Categorises
        </md-button>
      </div>
    </md-toolbar>

    <!-- Search Dialog -->
    <md-dialog :md-active.sync="showSearchDialog">
      <md-dialog-title>Search Headlines</md-dialog-title>

      <div class="md-layout" style="padding: 1em">
        <md-field>
          <label for="">Search Term(s)</label>
          <md-input v-model="query" placeholder="Use quotes for exact matches, AND / OR / NOW fro multiple terms" maxlength="30" />
        </md-field>
        <md-datepicker v-model="fromDate">
          <label for="">Select starting date(opt)</label>
        </md-datepicker>
        <md-datepicker v-model="toDate">
          <label for="">Select ending date(opt)</label>
        </md-datepicker>
        <md-field>
          <label for="">Sort search results by criteria(optional)</label>
          <md-select id="sortBy" v-model="sortBy" name="sortBy" md-dense>
            <md-option value="publishedAt">
              Newest (default)
            </md-option>
            <md-option value="relevany">
              Relevant
            </md-option>
            <md-option value="popularity">
              Popular
            </md-option>
          </md-select>
        </md-field>
      </div>

      <md-dialog-actions>
        <md-button @click="showSearchDialog=false" class="md-accent">
          Cancel
        </md-button>
        <md-button @click="searchHeadlines" class="md-primary">
          Search
        </md-button>
      </md-dialog-actions>
    </md-dialog>

    <md-drawer :md-active.sync="showLeftSidepanel" md-fixed>
      <md-toolbar :md-elevation="1">
        <span class="md-title">Personal Feed</span>
      </md-toolbar>

      <md-progress-bar v-if="loading" md-mode="indeterminate" />

      <md-field>
        <label for="country">Country</label>
        <md-select id="country" @input="changeCountry" :value="country" name="country">
          <md-option value="us">
            United States
          </md-option>
          <md-option value="ca">
            Canada
          </md-option>
          <md-option value="kr">
            Koread
          </md-option>
          <md-option value="ru">
            Russia
          </md-option>
          <md-option value="fr">
            France
          </md-option>
        </md-select>
      </md-field>

      <!-- Default Markup (if Feed Empty) -->
      <md-empty-state v-if="feed.length === 0 && !user" class="md-primary" md-icon="bookmarks" md-lable="Nothing in Feed" md-description="Logint to bookmark headlines">
        <md-button to="/login" class="md-primary md-raised">
          Login
        </md-button>
      </md-empty-state>

      <md-empty-state v-else-if="feed.length === 0" class="md-accent" md-icon="bookmark_outline" md-lable="Nothing in Feed" md-description="Anythig you bookmark will be safely stored here" />

      <!-- Feed Content -->
      <md-list v-else v-for="headline in feed" :key="headline.id" class="md-triple-line">
        <md-list-item>
          <md-avatar><img :src="headline.utlToImage" :alt="headline.title"></md-avatar>

          <div class="md-list-item-text">
            <span><a :href="headline.url" target="_blank">{{ headline.title }}</a></span>
            <span>{{ headline.source.name }}</span>
            <span @click="saveHeadline(headline)">View comments</span>
          </div>

          <md-button @click="removeHeadlineFromFeed(headline)" class="md-icon-button md-list-action">
            <md-icon class="md-accent">
              delete
            </md-icon>
          </md-button>
        </md-list-item>

        <md-divider class="md-inset" />
      </md-list>
    </md-drawer>

    <!-- News categories (Right Drawer) -->
    <md-drawer :md-active.sync="showRightSidepanel" class="md-right" md-fixed>
      <md-toolbar :md-elevation="1">
        <span class="md-title">News Categories</span>
      </md-toolbar>
      <md-progress-bar v-if="loading" md-mode="indeterminate" />
      <md-list>
        <md-subheader class="md-primary">
          Categories
        </md-subheader>
        <md-list-item v-for="(newsCategory, i) in newsCategories" :key="i" @click="loadCategory(newsCategory.path)">
          <md-icon :class="newsCategory.path === category ? 'md-primary' : ''">
            {{ newsCategory.icon }}
          </md-icon>
          <span class="md-list-item-text">{{ newsCategory.name }}</span>
        </md-list-item>
      </md-list>
    </md-drawer>

    <!-- App Content -->
    <div class="md-layout-item md-size-95">
      <md-content class="md-layout md-gutter" style="background: #007998; padding: 1em;">
        <ul v-for="headline in headlines" :key="headline.id" class="md-layout-item md-large-size-25 md-medium-size-33 md-small-size-50 md-xsmall-size-100">
          <md-card style="margin-top: 1em;" md-width-hover>
            <md-ripple>
              <md-card-media md-ratio="16:9">
                <img :src="headline.urlToImage" :alt="headlines.title">
              </md-card-media>
              <md-card-header>
                <div class="md-title">
                  <a :href="headline.url" target="_blank">{{ headline.title }}</a>
                </div>
                <div @click="loadSource(headline.source.id)">
                  {{ headline.source.name }}
                  <md-icon class="small-icon">
                    book
                  </md-icon>
                </div>
                <div v-if="headline.author" class="md-subhead">
                  {{ headline.author }}
                  <md-icon class="small-icon">
                    face
                  </md-icon>
                </div>
                <div class="md-subhead">
                  {{ headline.publishedAt | publishedTimeToNow }}
                  <md-icon class="small-icon">
                    alarm
                  </md-icon>
                </div>
              </md-card-header>

              <md-card-content>
                {{ headline.description }}
              </md-card-content>

              <md-card-actions>
                <md-button @click="addHeadlineToFeed(headline)" :class="isInFeed(headline.title)" class="md-icon-button">
                  <md-icon>bookmark</md-icon>
                </md-button>
                <md-button @click="saveHeadline(headline)" class="md-icon-button">
                  <md-icon>message</md-icon>
                </md-button>
              </md-card-actions>
            </md-ripple>
          </md-card>
        </ul>
      </md-content>
    </div>
  </div>
</template>

<script>
export default {
  // async asyncData ({ app }) {
  //   const topHeadlines = await app.$axios.$get('/api/top-headlines?country=us')
  //   return { headlines: topHeadlines.articles }
  // }
  data: () => ({
    showRightSidepanel: false,
    showLeftSidepanel: false,
    showSearchDialog: false,
    newsCategories: [
      { name: 'Top Headlines', path: '', icon: 'today' },
      { name: 'Technology', path: 'technology', icon: 'keyboard' },
      { name: 'Business', path: 'business', icon: 'business_center' },
      { name: 'Entertainment', path: 'entertainment', icon: 'weekend' },
      { name: 'Health', path: 'health', icon: 'fastfood' },
      { name: 'Scinence', path: 'science', icon: 'fingerprint' },
      { name: 'Sports', path: 'sports', icon: 'golf_course' }
    ],
    query: '',
    fromDate: '',
    toDate: '',
    sortBy: ''
  }),
  computed: {
    headlines () {
      return this.$store.getters.headlines
    },
    category () {
      return this.$store.getters.category
    },
    loading () {
      return this.$store.getters.loading
    },
    country () {
      return this.$store.getters.country
    },
    user () {
      return this.$store.getters.user
    },
    feed () {
      return this.$store.getters.feed
    },
    source () {
      return this.$store.getters.source
    },
    isAuthenticated () {
      return this.$store.getters.isAuthenticated
    }
  },
  watch: {
    async country () {
      await this.$store.dispatch('loadHeadLines', `/api/top-headlines?country=${this.country}&category=${this.category}`)
    }
  },
  async fetch ({ store }) {
    await store.dispatch('loadHeadLines', `/api/top-headlines?country=${store.state.country}&category=${store.state.category}`)
    await store.dispatch('loadUserFeed')
  },
  methods: {
    async loadCategory (category) {
      this.$store.commit('setCategory', category)
      await this.$store.dispatch('loadHeadLines', `/api/top-headlines?country=${this.country}&category=${this.category}`)
    },
    changeCountry (country) {
      this.$store.commit('setCountry', country)
    },
    logoutUser () {
      this.$store.dispatch('logoutUser')
    },
    async loadSource (sourceId) {
      if (sourceId) {
        this.$store.commit('setSource', sourceId)
        await this.$store.dispatch('loadHeadLines', `/api/top-headlines?sources=${this.source}`)
      }
    },
    async removeHeadlineFromFeed (headline) {
      await this.$store.dispatch('removeHeadlineFromFeed', headline)
    },
    async saveHeadline (headline) {
      await this.$store.dispatch('saveHeadline', headline).then(() => {
        this.$router.push(`/headlines/${headline.slug}`)
      })
    },
    async searchHeadlines () {
      await this.$store.dispatch('loadHeadLines', `/api/top-headlines?q=${this.query}&from=${this.dateToISOString(this.fromDate)}&to=${this.dateToISOString(this.toDate)}&sortBy=${this.sortBy}`)
      this.showSearchDialog = false
    },
    async addHeadlineToFeed (headline) {
      if (this.user) {
        await this.$store.dispatch('addHeadlineToFeed', headline)
      }
    },
    isInFeed (title) {
      const inFeed = this.feed.findIndex(headline => headline.title === title) > -1
      return inFeed ? 'md-primary' : ''
    },
    dateToISOString (date) {
      if (date) {
        return new Date(date).toISOString()
      }
    }
  }
}
</script>

<style  scoped>
  .small-icon {
    font-size: 18px !important;
  }

  .fixed-toolbar {
    position: fixed;
    top: 0;
    z-index: 5;
  }
</style>
