<i18n>
{
  "en": {
    "addBackendBtn": "Add Backend",
    "backendId": "id",
    "backendName": "name",
    "backends": "Backends",
    "backendType": "type",
    "checkConnection": "Check one connection | Check {0} connections",
    "checkConnectionTooltip": "Check connection",
    "deleteAreYouSure": "Are you sure you want to delete this backend? | Are you sure you want to delete those backends?",
    "editTooltip": "Edit",
    "editSyncTooltip": "Edit synchronization settings",
    "id": "ID",
    "name": "Name",
    "removeBackend": "Remove one backend | Remove {0} backends",
    "type": "Type"
  },
  "de": {
    "addBackendBtn": "Backend hinzufügen",
    "backends": "Backends",
    "backendId": "id",
    "backendName": "name",
    "backendType": "typ",
    "checkConnection": "Überprüfe eine Verbindung | Überprüfe {0} Verbindungen",
    "checkConnectionTooltip": "Verbindung überprüfen",
    "deleteAreYouSure": "Sind Sie sicher, dass sie dieses Backend Löschen wollen? | Sind sie sicher, dass sie diese Backends Löschen wollen?",
    "editTooltip": "Bearbeiten",
    "editSyncTooltip": "Synchronisationseinstellungen bearbeiten",
    "id": "ID",
    "name": "Name",
    "removeBackend": "Entferne ein Backend | Entferne {0} Backends",
    "type": "Type"
  }
}
</i18n>

<template>
  <v-container fill-height class="">
    <v-layout>
      <v-flex xl10 offset-xl1 lg12>
      <v-card class="tabbar-card">
        <v-tabs :dark="tabsDark" :background-color="tabsColor" :slider-color="tabsSliderColor"
          v-model="tab"
          grow
          hide-slider
        >
          <v-tab>
            <v-icon class="tabbar-tabicon">cloud</v-icon>{{ $t('backends') }}
          </v-tab>
        </v-tabs>
      </v-card>
      <v-tabs-items v-model="tab">
        <v-tab-item>
          <v-subheader>{{ $t('backends') }}</v-subheader>

            <v-card>
              <data-table v-model="selectedBackends" :headers="headers" :items="backends" @dblclick="$store.commit('backends/editBackend', $event.id)">
                <div slot="action" slot-scope="row" style="text-align: right">
                  <v-tooltip top open-delay="800">
                    <template v-slot:activator="{ on }">
                      <v-btn
                        text
                        icon
                        :loading="row.item.loading"
                        :disabled="row.item.loading"
                        :color="row.item.connection"
                        @click.stop="checkConnection(row.item)"
                        v-on="on"
                        :class="row.index === 0 ? 'mx-2 tutorial-element label-top-left element-icon' : 'mx-2'" style="--label-number: '4'"
                      ><v-icon>cached</v-icon></v-btn>
                    </template>
                    <span>{{ $t('checkConnectionTooltip') }}</span>
                  </v-tooltip>

                  <v-tooltip top open-delay="800">
                    <template v-slot:activator="{ on }">
                      <v-btn
                        text
                        icon
                        color="primary"
                        @click.stop="$store.commit('backends/editSync', row.item.id)"
                        v-on="on"
                       :class="row.index === 0 ? 'mx-2 tutorial-element label-top-left element-icon' : 'mx-2'" style="--label-number: '5'"
                      ><v-icon>settings_ethernet</v-icon></v-btn>
                    </template>
                    <span>{{ $t('editSyncTooltip') }}</span>
                  </v-tooltip>

                  <v-tooltip top open-delay="800">
                    <template v-slot:activator="{ on }">
                      <v-btn
                        text
                        icon
                        color="primary"
                        @click.stop="$store.commit('backends/editBackend', row.item.id)"
                        v-on="on"
                        :class="row.index === 0 ? 'mx-2 tutorial-element label-top-left element-icon' : 'mx-2'" style="--label-number: '6'"
                      ><v-icon>edit</v-icon></v-btn>
                    </template>
                    <span>{{ $t('editTooltip') }}</span>
                  </v-tooltip>
                </div>
              </data-table>
            </v-card>

            <div class="text-right">

              <v-btn
                color="primary"
                text
                @click="checkConnections(selectedBackends)"
                :disabled="selectedBackends.length === 0"
                class="ma-2 tutorial-element label-left" style="--label-number: '3'"
              >
                <v-icon left>cached</v-icon>{{ $tc('checkConnection', selectedBackends.length, [selectedBackends.length]) }}
              </v-btn>
              <v-btn
                color="error"
                text
                @click="$store.commit('backends/setDialog', true)"
                :disabled="selectedBackends.length === 0"
                class="ma-2 tutorial-element label-bottom" style="--label-number: '2'"
              >
                <v-icon left>remove_circle_outline</v-icon>{{ $tc('removeBackend', selectedBackends.length, [selectedBackends.length]) }}
              </v-btn>
              <v-btn
                color="success"
                text
                @click="$store.commit('backends/editBackend', 0)"
                class="ma-2 tutorial-element label-right" style="--label-number: '1'"
              >
                <v-icon left>add_circle_outline</v-icon>{{ $t('addBackendBtn') }}
              </v-btn>
            </div>

        </v-tab-item>
      </v-tabs-items>
      </v-flex>
    </v-layout>
    <v-dialog
      :value="$store.state.backends.dialog"
      @input="$store.commit('backends/setDialog', $event)"
      max-width="500px"
      scrollable
    >
      <v-card>
        <v-card-title class="elevation-3">
          <div>
            <div class="headline">{{ $tc('removeBackend', selectedBackends.length, [selectedBackends.length]) }}</div>
          </div>
        </v-card-title>
        <v-card-text>
          {{ $tc('deleteAreYouSure', selectedBackends.length) }}
            <template v-for="item in selectedBackends">
              <div class="grey--text" :key="item.id">[{{ item.id }}] {{ item.name }} ({{ item.type }})</div>
            </template>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn text="flat" @click="$store.commit('backends/setDialog', false)">{{ $t('cancel') }}</v-btn>
          <v-btn color="error" @click="$store.commit('backends/setDialog', false); deleteSelectedBackends()">{{ $t('delete') }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <backend-module-edit :backendId="$store.state.backends.backendId"/>
    <backend-module-sync :backendId="$store.state.backends.backendId"/>
  </v-container>
</template>

<script>
import BackendModuleEdit from '@/components/BackendModuleEdit'
import BackendModuleSync from '@/components/BackendModuleSync'
import DataTable from '@/components/DataTable'
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'BackendModule',
  components: {
    BackendModuleEdit,
    BackendModuleSync,
    DataTable
  },
  data () {
    return {
      dialog: false,
      backendName: '',
      backendId: '',
      backendType: '',
      edit: false,
      selectedBackends: [],
      tab: 0,
      headers: [
        { text: this.$t('id'), key: 'id' },
        { text: this.$t('name'), key: 'name' },
        { text: this.$t('type'), key: 'type' },
        { key: 'action' }
      ]
    }
  },
  methods: {
    async checkConnection (item) {
      // Set to start the loading animation.
      item.loading = true
      // Test the credential connection.
      try {
        const response = await this.$http.post('/api/backends/' + item.id + '/connection', {
          headers: {
            'Cache-Control': 'no-cache'
          }
        })
        // Set the button color to green if success.
        if (response) item.connection = 'success'
      } catch (error) {
        // Set the button color to red if error.
        item.connection = 'error'
        this.$snackbar({ color: 'error', text: error.response.data.message })
      }

      // Set item.loading = false to end the loading animation.
      item.loading = false
    },
    checkConnections (items) {
      const tmp = this
      items.forEach(function (item) {
        tmp.checkConnection(item)
      })
    },
    async deleteSelectedBackends () {
      // Filter selected array to get a list of ids.
      await this.$http.post('/api/backends/delete', {
        id: this.selectedBackends.map(x => x.id)
      })
      this.$store.dispatch('backends/loadData')
    }
  },
  computed: {
    ...mapGetters(['tabsDark', 'tabsColor', 'tabsSliderColor']),
    ...mapState('backends', ['backends'])
  },
  created () {
    this.$store.dispatch('backends/loadData')
  }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
