<template>
  <v-container>
    <v-layout>
      <v-flex xs6>
        <p class="caption font-weight-light font-italic">
          Choisir la landing page à afficher sur la page d'accueil.
        </p>
        <v-select
          v-model="currentLP"
          :items="docs"
          item-text="name"
          item-value="_id"
          label="Landing page"
          solo
          @change="updateCurrentLP()"
        />
      </v-flex>
    </v-layout>

    <v-layout>
      <v-flex xs6>
        <p class="caption font-weight-light font-italic">
          Editer une landing page.
          Pour ajouter une nouvelle landing page, passer par <b>Resources > Landing Page</b>
        </p>
      </v-flex>
    </v-layout>

    <v-list dense two-line class="elevation-2">
      <template v-for="item in docs">
        <v-list-item
          :key="`item-${item.coll}`"
          link
          nuxt
          :to="`/admin/landingpage/${item._id}`"
        >
          <v-list-item-content>
            <v-list-item-title v-text="item.name" />
            <v-list-item-subtitle v-text="item.description" />
          </v-list-item-content>

          <v-list-item-action />
        </v-list-item>
        <v-divider :key="`divider-${item.name}`" />
      </template>
    </v-list>
  </v-container>
</template>

<script>
export default {
  layout: 'admin',
  data: () => ({
    currentLP: '',
    docs: [],
    switch1: false
  }),
  mounted () {
    this.$store.commit('admin/ui/setTitle', 'Landing Page')
    this.$store.commit('admin/ui/setBreadcrumbs', [
      { text: 'Admin', to: '/admin' },
      { text: 'Landing Page', to: '/admin/landingpage' }
    ])
    this.getDocs()
    this.getCurrentLP()
  },
  methods: {
    getDocs () {
      this.$axios
        .get('/cloud/api/landingpages?projection=name:1,description:1')
        .then((res) => {
          this.docs = res.data.data
        })
    },
    getCurrentLP () {
      this.$axios
        .get('/cloud/api/config/home:landing-page')
        .then((res) => {
          try { this.currentLP = res.data.data.value } catch (e) {}
        })
    },
    updateCurrentLP () {
      this.$axios
        .put('/cloud/api/config/home:landing-page', { value: this.currentLP })
        .then((res) => {
          this.$store.commit('admin/ui/snack', { msg: 'Enregistré avec succès', color: 'success' })
        })
        .then((res) => {
          this.$store.commit('admin/ui/snack', { msg: 'Echec', color: 'error' })
        })
    }
  }
}
</script>
