<i18n>
{
  "en": {
    "blacklist": "Blacklist",
    "description": "Description",
    "groupdependent": "Groupdependent",
    "groups": "Groups",
    "id": "ID",
    "name": "Name",
    "permissions": "Permissions",
    "role": "Role",
    "roleName": "Role Name",
    "roleNameEmptyError": "Role Name can't be empty.",
    "roleSavedSuccess": "Role saved successfully.",
    "selectChildGroups": "Click to select all subgroups.",
    "submit": "Submit",
    "summary": "Summary"
  },
  "de": {
    "blacklist": "Blacklist",
    "description": "Beschreibung",
    "groupdependent": "Gruppengebunden",
    "groups": "Gruppen",
    "id": "ID",
    "name": "Name",
    "permissions": "Rechte",
    "role": "Rolle",
    "roleName": "Rollenname",
    "roleNameEmptyError": "Rollenname kann nicht leer sein.",
    "roleSavedSuccess": "Rolle erfolgreich gespeichert.",
    "selectChildGroups": "Klicke, um alle Untergruppen auszuwählen.",
    "submit": "Einreichen",
    "summary": "Zusammenfassung"
  }
}
</i18n>

<template>
  <v-card>
    <v-card-title style="padding: 0px; z-index: 1">
      <v-stepper v-model="step" horizontal  style="width: 100%; background: transparent;" class="elevation-3">
        <v-stepper-header>
          <v-stepper-step
            :complete="stepCompleted >= 1"
            step="1"
            :editable="stepCompleted >= 0"
            edit-icon="check"
          >
            {{ $t('role') }}
          </v-stepper-step>
          <v-divider></v-divider>
          <v-stepper-step
            :complete="stepCompleted >= 2"
            step="2"
            :editable="stepCompleted >= 1"
            edit-icon="check"
          >
            {{ $t('permissions') }}
          </v-stepper-step>
          <v-divider></v-divider>
          <v-stepper-step
            :complete="stepCompleted >= 3"
            step="3"
            :editable="stepCompleted >= 2"
            edit-icon="check"
          >
            {{ $t('groups') }}
          </v-stepper-step>
          <v-divider></v-divider>
          <v-stepper-step
            :complete="stepCompleted >= 4"
            step="4"
            :editable="stepCompleted >= 3"
            edit-icon="check"
          >
            {{ $t('blacklist') }}
          </v-stepper-step>
        </v-stepper-header>
      </v-stepper>
    </v-card-title>
    <v-card-text class="pa-0">
      <v-form v-model="valid" ref="form" @submit.prevent="submit" lazy-validation>
        <v-stepper v-model="step" horizontal style="width: 100%; background: transparent" class="elevation-0">
          <v-stepper-items>
            <v-stepper-content step="1">
              <v-layout wrap>
                <v-flex xs12 md5>
                  <v-text-field
                    :value="name"
                    @change="name = $event"
                    :label="$t('roleName')"
                    prepend-icon="label"
                    color="primary"
                    :rules="[v => !!v || $t('roleNameEmptyError')]"
                    ref="name"
                  ></v-text-field>
                </v-flex>
                <v-flex xs12 md5 offset-md1>
                  <v-textarea
                    :value="description"
                    @change="description = $event"
                    :label="$t('description')"
                    prepend-icon="description"
                    color="primary"
                    rows="1"
                    auto-grow
                  ></v-textarea>
                </v-flex>
              </v-layout>
            </v-stepper-content>

            <v-stepper-content step="2" class="stepper-padding-0">
              <data-table v-model="permissions" :headers="permissionHeaders" :items="permissionsList"/>
            </v-stepper-content>

            <v-stepper-content step="3" class="stepper-padding-0">
              <data-table v-model="groups" :headers="groupHeaders" :items="groupList" logging/>
            </v-stepper-content>

            <v-stepper-content step="4" class="stepper-padding-0">
              <data-table v-model="blacklist" :headers="groupHeaders" :items="blacklistList"/>
            </v-stepper-content>
          </v-stepper-items>
        </v-stepper>
      </v-form>
    </v-card-text>
    <v-divider></v-divider>
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn text @click.native="$store.commit('permissions/setDialog', { show : false } )">{{ $t('cancel') }}</v-btn>
      <v-btn :color="dialog.info.id ? 'primary' : 'success'" @click="submit" type="submit">{{ dialog.info.id ? $t('save') : $t('create') }}</v-btn>
      <v-btn color="primary" v-show="step == 1" @click.native="completeStepOne()">{{ $t('continue') }}</v-btn>
      <v-btn color="primary" v-show="step == 2" @click.native="completeStepTwo()">{{ $t('continue') }}</v-btn>
      <v-btn color="primary" v-show="step == 3 && groups.length > 0" @click.native="completeStepThree()">{{ $t('continue') }}</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
import DataTable from '@/components/DataTable'
import { mapState } from 'vuex'

export default {
  name: 'PermissionModuleEdit',
  components: {
    DataTable
  },
  data () {
    return {
      valid: true,
      step: 1,
      stepCompleted: 0,
      blacklistList: [],
      permissions: [],
      groups: [],
      blacklist: [],
      permissionHeaders: [
        { text: this.$t('name'), key: 'name' },
        { text: this.$t('description'), key: 'descr' },
        { text: this.$t('groupdependent'), key: 'groupdependent' }
      ],
      groupHeaders: [
        { text: this.$t('id'), key: 'id' },
        { text: this.$t('name'), key: 'name' },
        { text: this.$t('description'), key: 'description' }
      ],
      name: '',
      description: ''
    }
  },
  methods: {
    async submit (event) {
      await this.loadChilds()
      if (this.$refs.form.validate()) {
        const url = this.dialog.info.id === undefined ? '/api/roles' : '/api/roles/' + this.dialog.info.id
        await this.$http.post(url, {
          name: this.name,
          description: this.description,
          permissions: this.permissions.map(x => x.id),
          groups: this.groups.map(x => x.id),
          blacklist: this.blacklist.map(x => x.id)
        })
        this.$snackbar({ color: 'success', text: this.$t('roleSavedSuccess') })
        this.$store.dispatch('permissions/loadRoles')
        this.$store.dispatch('users/loadData')
        this.$store.commit('permissions/setDialog', { show: false })
      } else {
        this.$snackbar({ color: 'error', text: this.$t('roleNameEmptyError') })
      }
    },
    completeStepOne () {
      if (this.$refs.form.validate()) {
        this.step = 2
        this.stepCompleted = Math.max(1, this.stepCompleted)
      }
    },
    completeStepTwo () {
      this.step = 3
      this.stepCompleted = Math.max(2, this.stepCompleted)
    },
    completeStepThree () {
      this.loadChilds()
      this.step = 4
      this.stepCompleted = Math.max(3, this.stepCompleted)
    },
    async loadChilds () {
      if (this.groups.length > 0) {
        var response = await this.$http.post('/api/events/blacklist', { groups: this.groups })
        this.blacklistList = response.data.subgroups
        this.blacklist = this.blacklist.filter(g => this.blacklistList.map(x => x.id).indexOf(g.id) !== -1)
      } else {
        this.blacklist = []
        this.blacklistList = []
      }
    }
  },
  computed: {
    ...mapState('permissions', ['dialog', 'permissionsList']),
    ...mapState('groups', ['groupList'])
  },
  watch: {
    step (val) {
      if (val === '3') this.loadChilds()
    },
    dialog: {
      immediate: true,
      deep: true,
      handler (value) {
        if (value.type === 'edit' && value.show) {
          if (this.$refs.form) this.$refs.form.resetValidation()
          this.step = 1
          this.stepCompleted = value.info.id ? 4 : 0
          this.name = value.info.name || ''
          this.description = value.info.descr || ''
          this.permissions = value.info.permissions || []
          this.groups = []
          this.blacklist = []
          this.blacklistList = []
          if (value.info.groups) {
            var groupsPush = []
            for (let i = 0; i < value.info.groups.length; i++) {
              if (value.info.groups[i].role_x_group.blacklist) groupsPush.push(value.info.groups[i])
              else this.groups.push(value.info.groups[i])
            }
            this.loadChilds().then(() => {
              this.blacklist = groupsPush
            })
          }
        }
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.stepper-padding-0 {
  padding: 0;
}
</style>
