<template>
  <div class="container">
    <section class="section">


      <h1 class="title">{{ $t('Manage_rooms') }}</h1>
      <p class="lead">
        {{ $t('List_create_and_delete') }} <strong>{{ $t('rooms') }}</strong>
      </p>
      <br/>

      <b-tabs v-model="tabIndex" card>
        <b-tab title="Room list" active>
          <template slot="title">
            <font-awesome-icon icon="list"/>&nbsp;<font-awesome-icon icon="door-open"/>
            <strong>Room</strong>&nbsp;<i>list</i>
          </template>
          <div class="mt-3">
            <b-button-group>
              <b-button variant="success" @click="showAllRooms()">{{ $t('All rooms') }}</b-button>
              <b-button variant="info" @click="showRoomsWithRecorder()">{{ $t('Rooms with recorders') }}</b-button>
              <b-button variant="warning" @click="showRoomsWithoutRecorder()">{{ $t('Rooms without recorders') }}
              </b-button>
            </b-button-group>
          </div>
          <p>{{ $tc('rooms_defined', rooms.length, {num: rooms.length}) }}:</p>
          <b-card-group deck>
            <b-card class="mb-2" style="max-width: 30rem; min-width:20rem;" v-for="(room) in rooms"
                    :header="room.name + ' (' +room.building_number+ ')'" v-bind:key="room.id">
              <b-card-text>
                <h5 class="card-title"><strong>{{ $t('name') }}</strong>:&nbsp;
                  <span v-if="!formEditField[room.id+'_name']">{{ room.name }}&nbsp;
                                        <a class="float-right badge badge-pill badge-primary">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'name')"
                                                icon="pencil-alt"/>
                                        </a>
                                    </span>
                  <b-input-group v-else>
                    <ValidationProvider v-slot="{ errors }">
                      <b-form-input :id="room.id+'_name'" name="name"
                                    v-model="updateValues[room.id+'_name']"
                                    v-validate="'required|min:3'"
                                    v-bind:class="{'is-danger': errors.has('name'), 'is-invalid': errors.has('name')}"
                                    class="form-control" type="text"
                                    :placeholder="'Name ('+room.name +')'"
                                    required></b-form-input>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('name')"
                                  @click="updateRoom(room.id, 'name')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>
                </h5>


                <p class="card-text"><strong>{{ $t('building_number') }}</strong>:&nbsp;
                  <span v-if="!formEditField[room.id+'_building_number']">{{ room.building_number }}&nbsp;
                                        <a class="float-right badge badge-pill badge-primary">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'building_number')"
                                                icon="pencil-alt"/>
                                        </a>
                                    </span>
                  <b-input-group v-else>
                    <ValidationProvider v-slot="{ errors }">
                      <b-form-input :id="room.id+'_building_number'" name="building_number"
                                    v-model="updateValues[room.id+'_building_number']"
                                    v-validate="'required|min:3'"
                                    v-bind:class="{'is-danger': errors.has('building_number'), 'is-invalid': errors.has('building_number')}"
                                    class="form-control" type="text"
                                    :placeholder="$t('Building_number') +'('+room.building_number +')'"
                                    required></b-form-input>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('building_number')"
                                  @click="updateRoom(room.id, 'building_number')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>
                </p>
                <p class="card-text"><strong>{{ $t('building_name') }}</strong>:&nbsp;
                  <span v-if="!formEditField[room.id+'_building_name']">{{ room.building_name }}&nbsp;
                                        <a class="float-right badge badge-pill badge-primary">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'building_name')"
                                                icon="pencil-alt"/>
                                        </a>
                                    </span>
                  <b-input-group v-else>
                    <ValidationProvider v-slot="{ errors }">
                      <b-form-input :id="room.id+'_building_name'" name="building_name"
                                    v-model="updateValues[room.id+'_building_name']"
                                    v-validate="'required|min:3'"
                                    v-bind:class="{'is-danger': errors.has('building_name'), 'is-invalid': errors.has('building_name')}"
                                    class="form-control" type="text"
                                    :placeholder="'Building name ('+room.building_name +')'"
                                    required></b-form-input>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('building_name')"
                                  @click="updateRoom(room.id, 'building_name')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>
                </p>


                <p class="card-text"><strong>{{ $t('alternate_name') }}:</strong>&nbsp;
                  <span v-if="!formEditField[room.id+'_alternate_name']">{{ room.alternate_name }}&nbsp;
                                        <a class="float-right badge badge-pill badge-info">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'alternate_name')"
                                                icon="pencil-alt"/>
                                        </a>
                                    </span>
                  <b-input-group v-else size="sm">
                    <ValidationProvider v-slot="{ errors }">
                      <b-form-input name="alternate_name"
                                    v-model="updateValues[room.id+'_alternate_name']"
                                    class="form-control" type="text"
                                    :placeholder="'Alternate name ('+room.alternate_name +')'"
                                    @blur="updateRoom(room.id, 'alternate_name')"
                                    @keyup.enter="updateRoom(room.id, 'alternate_name')"></b-form-input>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('alternate_name')"
                                  @click="updateRoom(room.id, 'alternate_name')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>
                </p>
                <p class="card-text"><strong>{{ $t('room_number') }}:</strong>&nbsp;
                  <span v-if="!formEditField[room.id+'_number']">{{ room.number }}&nbsp;
                                        <a class="float-right badge badge-pill badge-info">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'number')"
                                                icon="pencil-alt"/>
                                        </a>
                                    </span>
                  <b-input-group v-else size="sm">
                    <ValidationProvider v-slot="{ errors }">
                      <b-form-input name="number"
                                    v-model="updateValues[room.id+'_number']"
                                    v-validate="'required|min:3'"
                                    v-bind:class="{'is-danger': errors.has('name'), 'is-invalid': errors.has('name')}"
                                    class="form-control" type="text"
                                    :placeholder="'Room number ('+room.number +')'"
                                    @blur="updateRoom(room.id, 'number')"
                                    @keyup.enter="updateRoom(room.id, 'number')"
                                    required></b-form-input>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('number')"
                                  @click="updateRoom(room.id, 'number')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>
                </p>
                <p class="card-text">
                  <small><strong>{{ $t('comment') }}:</strong>&nbsp;
                    <span v-if="!formEditField[room.id+'_comment']">{{ room.comment }}&nbsp;
                                        <a class="float-right badge badge-pill badge-info">
                                            <font-awesome-icon
                                                @click="initRoomUpdate(room, 'comment')"
                                                icon="pencil-alt"/>
                                        </a>
                                        </span>
                    <textarea class="textarea form-control" v-else name="comment"
                              v-model="updateValues[room.id+'_comment']"
                              :placeholder="'Comment ('+room.comment +')'"
                              @blur="updateRoom(room.id, 'comment')"></textarea>
                  </small>
                </p>
                <hr/>
                <span v-if="!formEditField[room.id+'_recorder_id']">{{ room.recorder_id }}&nbsp;
                                    <div v-if="room.recorder">
                                        <p class="card-text"><strong>{{
                                            $t('Recorder')
                                          }}:</strong>&nbsp;{{ room.recorder.name }}&nbsp;
                                            ({{ room.recorder.ip }}) / ({{ room.recorder.network_name }})</p>
                                    </div>
                                    <div v-else>
                                        <p class="card-text"><strong>{{ $t('Recorder') }}:</strong>&nbsp;{{
                                            $t('no_recorder_defined')
                                          }}</p>
                                    </div>
                                    <a class="float-right badge badge-pill badge-info">
                                        <font-awesome-icon
                                            @click="initRoomUpdate(room, 'recorder_id')" icon="pencil-alt"/>
                                    </a>
                                </span>
                <b-form v-else>
                  <b-input-group>
                    <ValidationProvider v-slot="{ errors }">
                      <select class="form-control" v-model="updateValues[room.id+'_recorder_id']">
                        <option value="">No recorder selected</option>
                        <option v-for="recorder in recorders" v-bind:value="recorder.id">
                          {{ recorder.name }}
                        </option>
                      </select>
                      <b-input-group-append>
                        <b-button :disabled="errors.has('recorder_id')"
                                  @click="updateRoom(room.id, 'recorder_id')"
                                  variant="outline-success">
                          <font-awesome-icon icon="check"></font-awesome-icon>
                        </b-button>
                      </b-input-group-append>
                    </ValidationProvider>
                  </b-input-group>

                  <div class="form-check">
                    <input class="form-check-input" type="checkbox"
                           v-model="show_assigned_recorders" id="defaultCheck1">
                    <label class="form-check-label" for="defaultCheck1">
                      Show already assigned recorders
                    </label>
                  </div>
                </b-form>

              </b-card-text>
              <div slot="footer">
                <small class="text-muted">
                  <p>{{ $t('created') }}: {{ room.created_at | moment("dddd, MMMM Do YYYY") }}
                    <span class="pull-right">
                                            <button type="button" v-on:click="deleteRoom(room.id)"
                                                    class="btn btn-sm btn-danger">{{
                                                $t('delete')
                                              }}&nbsp;<font-awesome-icon
                                                  icon="trash"/>
                                            </button>
                                        </span>
                  </p>
                </small>
              </div>
            </b-card>
          </b-card-group>
        </b-tab>

        <b-tab title="Create room">
          <template slot="title">
            <font-awesome-icon icon="plus"/>
            <i>{{ $t('create') }}</i>&nbsp;<font-awesome-icon icon="door-open"/>
            <strong>{{ $t('Room') }}</strong>
          </template>
          <b-card-text>
            <p>{{ $t('Create_a_new_room') }}:</p>
            <!-- form starts here -->
            <ValidationObserver v-slot="{ invalid }">
              <form v-on:submit.prevent="saveRoom()">
                <section class="form">

                  <ValidationProvider :name="$t('name')" rules="required|min:3" v-slot="{ errors }" slim>
                    <div class="form-group row">
                      <label class="label required col-sm-2 col-form-label">{{ $t('name') }}</label>

                      <div class="col-sm-6">
                        <input name="name"
                               v-model="form.name"
                               v-bind:class="{'is-danger': errors.length > 0, 'is-invalid': errors.length > 0}"
                               class="form-control" type="text" placeholder="Room name" required>
                      </div>
                      <p class="col-sm-4" v-show="errors.length > 0">
                        {{ errors[0] }}
                      </p>

                    </div>
                  </ValidationProvider>

                  <div class="form-group row">
                    <label class="label col-sm-2 col-form-label">{{ $t('alternate_name') }}</label>
                    <div class="col-sm-6">
                      <input name="alternate_name"
                             v-model="form.alternate_name"
                             class="form-control" type="text" placeholder="Alternate name">
                    </div>
                  </div>

                  <ValidationProvider :name="$t('number')" rules="required|min:3" v-slot="{ errors }" slim>
                    <div class="form-group row">
                      <label class="label required col-sm-2 col-form-label">{{ $t('number') }}</label>

                      <div class="col-sm-6">
                        <input name="number"
                               v-model="form.number"
                               v-bind:class="{'is-danger': errors.length > 0, 'is-invalid': errors.length > 0}"
                               class="form-control" type="text" placeholder="Room number" required>
                      </div>
                      <p class="col-sm-4" v-show="errors.length > 0">
                        {{ errors[0] }}
                      </p>

                    </div>
                  </ValidationProvider>

                  <div class="form-group row">
                    <label class="label col-sm-2 col-form-label">{{ $t('comment') }}</label>
                    <div class="col-sm-6">
                            <textarea class="textarea form-control"
                                      :placeholder="$t('Comments') +', ' + $t('notes') + ', etc.'"
                                      v-model="form.comment"></textarea>
                    </div>
                  </div>

                  <div class="form-group row">
                    <label class="label col-sm-2 col-form-label">{{ $t('recorder') }}</label>
                    <div class="col-sm-6">
                      <select class="form-control" v-model="form.recorder_id">
                        <option value="">No recorder selected</option>
                        <option v-for="recorder in recorders" v-bind:value="recorder.id">
                          {{ recorder.name }}
                        </option>
                      </select>
                    </div>
                  </div>


                  <div class="field is-grouped">
                    <div class="control">
                      <button
                          v-bind:disabled="invalid"
                          type="submit"
                          class="btn btn-primary">
                        Create room
                      </button>
                    </div>
                  </div>

                </section>
              </form>
            </ValidationObserver>
          </b-card-text>
        </b-tab>
      </b-tabs>
    </section>

    <hr>

    <div class="column">
      <section class="section" id="results">
        <div class="box">
          <ul>
            <!-- loop through all the `form` properties and show their values -->
            <li v-for="(item, k) in form">
              <strong>{{ k }}:</strong> {{ item }}
            </li>
          </ul>
        </div>
      </section>
    </div>

    <div class="column">
      <section class="section">
        {{ rooms }}
      </section>
    </div>

  </div>
</template>

<script>
import {EventBus} from '@/utils';
import PulseLoader from 'vue-spinner/src/PulseLoader.vue';
import getRepository from '@/api/RepositoryFactory';

const RoomRepository = getRepository('room');

export default {
  components: {
    PulseLoader,
  },
  props: [],
  data() {
    return {
      onlyShowRoomsWithRecorder: false,
      onlyShowRoomsWithoutRecorder: false,
      tabIndex: 0,
      updateValues: {},
      formEditField: {},
      show_assigned_recorders: false,
      form: {
        name: null,
        alternate_name: null,
        number: null,
        comment: null,
        recorder_id: null,
      },
    };
  },
  methods: {
    showAllRooms() {
      this.onlyShowRoomsWithRecorder = false;
      this.onlyShowRoomsWithoutRecorder = false;
    },
    showRoomsWithRecorder() {
      this.onlyShowRoomsWithRecorder = true;
      this.onlyShowRoomsWithoutRecorder = false;
    },
    showRoomsWithoutRecorder() {
      this.onlyShowRoomsWithRecorder = false;
      this.onlyShowRoomsWithoutRecorder = true;
    },
    saveRoom() {
      this.$parent.$data.isLoading = true;
      RoomRepository.createRoom(this.form)
          .then(() => {
            this.$store.dispatch('loadRooms')
                .then(() => {
                  this.$parent.$data.isLoading = false;
                  this.tabIndex = 0;
                });
          }).catch((msg) => {
        this.showErrorMessage('Could not safe room!');
      });
    },
    initRoomUpdate(room, fieldName) {
      this.$set(this.formEditField, room.id + '_' + fieldName, true);
      this.$set(this.updateValues, room.id + '_' + fieldName, room[fieldName]);
    },
    updateRoom(id, fieldName) {
      this.$parent.$data.isLoading = true;
      const data = {};
      data[fieldName] = this.updateValues[id + '_' + fieldName];
      RoomRepository.updateRoom(id, data)
          .then(() => {
            this.$store.dispatch('loadRooms')
                .then(() => {
                  this.$parent.$data.isLoading = false;
                  this.formEditField[id + '_' + fieldName] = false;
                });
          });
    },
    deleteRoom(id) {
      this.$parent.$data.isLoading = true;
      RoomRepository.deleteRoom(id)
          .then(() => {
            this.$store.dispatch('loadRooms')
                .then(() => {
                  this.$parent.$data.isLoading = false;
                });
          });
    },
    showErrorMessage(msg) {
      this.$parent.$data.isLoading = false;
      this.$parent.$data.showAlert = true;
      this.$parent.$data.alertMessage = msg;
    },
  },
  mounted() {
    this.$parent.$data.isLoading = true;
    this.$parent.$data.showAlert = false;
    this.$store.dispatch('loadRooms')
        .then(() => {
          this.$store.dispatch('loadRecorders')
              .then(() => {
                this.$parent.$data.isLoading = false;
              });
        });
  },
  computed: {
    options() {
      return {
        recorders: [
          {value: 8, text: 'SMP 351 AudiMax'},
          {value: 13, text: 'SMP 351 HMU'},
        ],
      };
    },
    rooms() {
      if (this.onlyShowRoomsWithRecorder) {
        return this.$store.state.rooms.filter((item) => {
          return item.recorder;
        });
      } else if (this.onlyShowRoomsWithoutRecorder) {
        return this.$store.state.rooms.filter((item) => {
          return !item.recorder;
        });
      }
      return this.$store.state.rooms;
    },
    recorders() {
      return this.$store.state.recorders;
    },
  },
};
</script>

<style>
.comment {
  white-space: pre-wrap;
}

.card:hover {
  background-color: whitesmoke;
}

.required:after {
  content: " *";
}
</style>
