<i18n>
{
  "en": {
  },
  "de": {
  }
}
</i18n>

<template>
  <v-dialog
    :value="$store.state.permissions.edit"
    @input="$store.commit('permissions/setEdit', $event)"
    max-width="700px"
    scrollable
  >
    <v-card>
      <v-card-title style="padding: 0px">
        <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 >= 1"
              edit-icon="check"
            >
              {{ $t('role') }}
            </v-stepper-step>
            <v-divider></v-divider>
            <v-stepper-step
              :complete="stepCompleted >= 2"
              step="2"
              :editable="stepCompleted >= 2"
              edit-icon="check"
            >
              {{ $t('permissions') }}
            </v-stepper-step>
            <v-divider></v-divider>
            <v-stepper-step
              :complete="stepCompleted >= 3"
              step="3"
              :editable="stepCompleted >= 3"
              edit-icon="check"
            >
              {{ $t('groups') }}
            </v-stepper-step>
            <v-divider></v-divider>
            <v-stepper-step
              :complete="stepCompleted >= 4"
              step="4"
              :editable="stepCompleted >= 4"
              edit-icon="check"
            >
              {{ $t('confirm') }}
            </v-stepper-step>
          </v-stepper-header>
        </v-stepper>
      </v-card-title>
      <v-card-text style="height: 500px;">
        <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-text-field
                  v-model="roleName"
                  :label="$t('roleName')"
                  prepend-icon="label"
                  class="info-input"
                  color="primary"
                  :rules="[() => !!roleName || $t('roleNameEmptyError')]"
                  ref="roleName"
                ></v-text-field>

                <v-textarea
                  v-model="roleDescr"
                  :label="$t('description')"
                  prepend-icon="description"
                  class="info-input"
                  color="primary"
                  rows="1"
                  auto-grow
               ></v-textarea>

              </v-stepper-content>

              <v-stepper-content step="2">
               <v-data-table
                  :headers="permissionHeaders"
                  :items="permissions"
                  item-key="id"
                  hide-actions
                  select-all
                  :value="permissionsSelected"
                  @input="setPermissionsSelected($event)"
                >
                  <template slot="items" slot-scope="props">
                    <tr @click="props.selected = !props.selected">
                      <td>
                        <v-checkbox
                          color="primary"
                          v-model="props.selected"
                          hide-details
                          @click.native.stop
                        ></v-checkbox>
                      </td>
                      <td hidden>{{ props.item.id }}</td>
                      <td>{{ props.item.name }}</td>
                      <td>{{ props.item.descr }}</td>
                      <td>{{ props.item.groupdependent }}</td>
                    </tr>
                  </template>
                </v-data-table>
              </v-stepper-content>

              <v-stepper-content step="3">
               <v-data-table
                  :headers="groupHeaders"
                  :items="groups"
                  item-key="id"
                  hide-actions
                  select-all
                  :value="groupsSelected"
                  @input="setGroupsSelected($event)"
                >
                  <template slot="items" slot-scope="props">
                    <tr @click="props.selected = !props.selected">
                      <td>
                        <v-checkbox
                          color="primary"
                          v-model="props.selected"
                          hide-details
                          @click.native.stop
                        ></v-checkbox>
                      </td>
                      <td>{{ props.item.id }}</td>
                      <td>{{ props.item.name }}</td>
                      <td>{{ props.item.description }}</td>
                    </tr>
                  </template>
                </v-data-table>
              </v-stepper-content>

              <v-stepper-content step="4">
                <v-text-field
                  v-model="roleName"
                  :label="$t('roleName')"
                  prepend-icon="label"
                  class="info-input"
                  color="primary"
                  :rules="[() => !!roleName || $t('roleNameEmptyError')]"
                  ref="roleName"
                  disabled
                ></v-text-field>

                <v-textarea
                  v-model="roleDescr"
                  :label="$t('description')"
                  prepend-icon="description"
                  class="info-input"
                  color="primary"
                  rows="1"
                  auto-grow
                  disabled
               ></v-textarea>

                <v-layout row wrap>
                  <v-flex>
                    <v-list subheader>
                      <v-subheader inset>{{ $t('permissions') }}</v-subheader>
                      <v-divider class="list-header-margin"></v-divider>
                      <v-list-tile
                        v-for="permission in permissionsSelected"
                        :key="permission.id"
                      >
                        <v-list-tile-content>
                          <v-list-tile-title>{{ permission.name }}</v-list-tile-title>
                          <v-list-tile-sub-title>{{ permission.descr }}</v-list-tile-sub-title>
                        </v-list-tile-content>
                      </v-list-tile>
                    </v-list>
                  </v-flex>
                  <v-flex>
                    <v-list subheader>
                      <v-subheader inset>{{ $t('groups') }}</v-subheader>
                      <v-divider class="list-header-margin"></v-divider>
                      <v-list-tile
                        v-for="group in groupsSelected"
                        :key="group.id"
                      >
                        <v-list-tile-content>
                          <v-list-tile-title>{{ group.id }} {{ group.name }}</v-list-tile-title>
                          <v-list-tile-sub-title>{{ group.description }}</v-list-tile-sub-title>
                        </v-list-tile-content>
                      </v-list-tile>
                    </v-list>
                  </v-flex>
                </v-layout>
              </v-stepper-content>

            </v-stepper-items>
          </v-stepper>
        </v-form>
      </v-card-text>
      <v-divider></v-divider>
      <v-card-actions>
        <v-flex xl10 offset-xl1 lg12 text-xs-right>
          <v-btn flat @click.native="$store.commit('permissions/setEdit', false )">{{ $t('cancel') }}</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" @click.native="completeStepThree()">{{ $t('continue') }}</v-btn>
          <v-btn class="success" v-show="step == 4" @click="submit" type="submit">{{ $t('submit') }}</v-btn>
        </v-flex>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>

export default {
  name: 'PermissionModuleEdit',
  props: ['roleId'],
  data () {
    return {
      valid: true,
      step: 1,
      stepCompleted: 0,
      permissions: [],
      groups: [],
      permissionsSelected: [],
      groupsSelected: [],
      permissionHeaders: [
        { text: 'Name', value: 'name' },
        { text: 'Description', value: 'descr' },
        { text: 'Groupdependent', value: 'groupdependent' }
      ],
      groupHeaders: [
        { text: 'ID', value: 'id' },
        { text: 'Name', value: 'name' },
        { text: 'Description', value: 'description' }
      ],
      roleName: '',
      roleDescr: ''
    }
  },
  methods: {
    submit (event) {
      if (this.$refs.form.validate()) {
        const filteredPermissions = this.permissionsSelected.map(x => x.id)
        const filteredGroups = this.groupsSelected.map(x => x.id)
        this.$http.post('/api/permissions/saveRole', {
          id: this.roleId,
          name: this.roleName,
          descr: this.roleDescr,
          permissions: filteredPermissions,
          groups: filteredGroups
        }).then(response => {
          // TODO: Add backend saved successfull msg.
          console.log('TODO: Implement snackbar and print role saved successfully msg.')
          this.$store.dispatch('permissions/loadData')
          this.$store.commit('permissions/setEdit', false)
        }).catch(error => {
          console.log(error)
        })
      }
    },
    loadRole (roleId) {
      this.$http('/api/permissions/getRoleById?id=' + this.roleId).then(response => {
        this.roleName = response.data.name
        this.roleDescr = response.data.descr
        this.permissionsSelected = response.data.permissions
        this.groupsSelected = response.data.groups
      })
    },
    completeStepOne () {
      if (this.roleName !== '') {
        this.step = 2
        this.stepCompleted = Math.max(1, this.stepCompleted)
      } else {
        this.$refs.form.validate()
      }
    },
    completeStepTwo () {
      this.step = 3
      this.stepCompleted = Math.max(2, this.stepCompleted)
    },
    completeStepThree () {
      this.step = 4
      this.stepCompleted = Math.max(3, this.stepCompleted)
    },
    setPermissionsSelected (value) {
      this.permissionsSelected = value
    },
    setGroupsSelected (value) {
      this.groupsSelected = value
    },
    loadGroups () {
      this.$http('/api/groups/getAll').then(response => {
        this.groups = response.data
      })
    },
    loadPermissions () {
      this.$http('/api/permissions/getPermissionList').then(response => {
        this.permissions = response.data
      })
    }
  },
  computed: {
    edit: function () {
      return this.$store.state.permissions.edit
    }
  },
  watch: {
    edit: function (value) {
      if (value) {
        this.loadGroups()
        this.$refs.form.reset()
        this.permissionsSelected = []
        this.groupsSelected = []
        this.step = 1
        this.stepCompleted = 0
        if (this.roleId !== 0) {
          this.loadRole(this.roleId)
        } else {
          this.roleName = ''
          this.roleDescr = ''
        }
      }
    }
  },
  created () {
    this.loadPermissions()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.info-input {
  margin: 20px;
}
.list-header-margin {
  margin-bottom: 10px;
}
</style>
