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


            <h1 class="title">{{ $t('Manage Commands') }}</h1>
            <p class="lead">
                {{ $t('List, create and delete') }} <strong>{{ $t('commands') }}</strong>
            </p>
            <br/>

            <b-tabs v-model="tabIndex" card>
                <b-tab title="Command list" active>
                    <template slot="title">
                        <font-awesome-icon icon="list"/>&nbsp;<font-awesome-icon icon="cogs"/>
                        <strong>command</strong>&nbsp;<i>list</i>
                    </template>
                    <p>{{ $t('There are')}}&nbsp;{{commands.length}}&nbsp;{{ $t('recorder commands defined')}}:</p>
                    <b-card-group deck>
                        <b-card class="mb-2" style="max-width: 30rem; min-width:20rem;" v-for="(command) in commands"
                                :header="command.name + ' (' +command.recorder_model.name+ ')'" v-bind:key="command.id">
                            <b-card-text>
                                <h5 class="card-title">{{ $t('name') }}:&nbsp;
                                    <span>{{command.name}}&nbsp;</span>
                                </h5>

                                <p class="card-text">
                                    <small><strong>{{ $t('alternative_name') }}:</strong>&nbsp;
                                        <span v-if="!formEditField[command.id+'_alternative_name']">{{command.alternative_name}}&nbsp;
                                        <a class="float-right badge badge-pill badge-primary">
                                            <font-awesome-icon
                                                    @click="initRecCommandUpdate(command, 'alternative_name')"
                                                    icon="pencil-alt"/>
                                        </a>
                                    </span>
                                        <b-input-group v-else>
                                            <b-form-input :id="command.id+'_alternative_name'" name="alternative_name"
                                                          v-model="updateValues[command.id+'_alternative_name']"
                                                          v-validate="'required|min:3'"
                                                          v-bind:class="{'is-danger': errors.has('alternative_name'), 'is-invalid': errors.has('alternative_name')}"
                                                          class="form-control" type="text"
                                                          :placeholder="'Alternative name ('+command.alternative_name +')'"
                                                          required></b-form-input>
                                            <b-input-group-append>
                                                <b-button :disabled="errors.has('alternative_name')"
                                                          @click="updateRecCommand(command.id, 'alternative_name')"
                                                          variant="outline-success">
                                                    <font-awesome-icon icon="check"></font-awesome-icon>
                                                </b-button>
                                            </b-input-group-append>
                                        </b-input-group>
                                    </small>
                                </p>
                                <p class="card-text">
                                    <small><strong>{{ $t('description') }}:</strong>&nbsp;
                                        <span v-if="!formEditField[command.id+'_description']">{{command.description}}&nbsp;
                                        <a class="float-right badge badge-pill badge-info">
                                            <font-awesome-icon
                                                    @click="initRecCommandUpdate(command, 'description')"
                                                    icon="pencil-alt"/>
                                        </a>
                                        </span>
                                        <textarea class="textarea form-control" v-else name="comment"
                                                  v-model="updateValues[command.id+'_description']"
                                                  :placeholder="'Comment ('+command.description +')'"
                                                  @blur="updateRecCommand(command.id, 'description')"></textarea>
                                    </small>
                                </p>
                                <hr/>

                                    <div v-if="command.recorder_model">
                                        <p class="card-text"><strong>{{ $t('Recorder') }} {{ $t('model') }}:</strong>&nbsp;{{command.recorder_model.name}}&nbsp;</p>
                                    </div>
                                    <div v-else>
                                        <p class="card-text"><strong>{{ $t('Recorder') }}:</strong>&nbsp;{{
                                            $t('no_recorder_model_defined')}}</p>
                                    </div>



                            </b-card-text>
                            <div slot="footer">
                                <small class="text-muted">
                                    <p>{{ $t('created')}}: {{command.created_at | moment("dddd, MMMM Do YYYY")}}
                                        
                                    </p>
                                </small>
                            </div>
                        </b-card>
                    </b-card-group>
                </b-tab>

                <b-tab title="Create command">
                    <template slot="title">
                        <font-awesome-icon icon="plus"/>
                        <i>{{$t('create')}}</i>&nbsp;<font-awesome-icon icon="cogs"/>
                        <strong>{{$t('virtual')}} {{$t('command')}}</strong>
                    </template>
                    <b-card-text>
                        <p>{{ $t('Create a new command')}}:</p>
                        <!-- form starts here -->
                        <form v-on:submit.prevent="savecommand()">
                            <section class="form">

                                <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-validate="'required|min:3'"
                                               v-bind:class="{'is-danger': errors.has('name'), 'is-invalid': errors.has('name')}"
                                               class="form-control" type="text" placeholder="command name" required>
                                    </div>
                                    <p class="col-sm-4" v-show="errors.has('name')">
                                        {{ errors.first('name') }}
                                    </p>
                                </div>

                                <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>

                                <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-validate="'required|min:3'"
                                               v-bind:class="{'is-danger': errors.has('number'), 'is-invalid': errors.has('number')}"
                                               class="form-control" type="text" placeholder="command number" required>
                                    </div>
                                    <p class="col-sm-4" v-show="errors.has('number')">
                                        {{ errors.first('number') }}
                                    </p>
                                </div>

                                <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="Comments, remarks, 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="errors.any()"
                                                type="submit"
                                                class="btn btn-primary">
                                            Create command
                                        </button>
                                    </div>
                                </div>

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

        <hr>

        <!--
        <div class="column">
            <section class="section" id="results">
                <div class="box">
                    <ul>
                        <li v-for="(item, k) in form">
                            <strong>{{ k }}:</strong> {{ item }}
                        </li>
                    </ul>
                </div>
            </section>
        </div>

        <div class="column">
            <section class="section">
                {{recorders}}
            </section>
        </div>
        -->

    </div>
</template>

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

    const recorderRepository = getRepository('recorder');
    const commandRepository = getRepository('command');

    export default {
        components: {
            PulseLoader,
        },
        props: [],
        data() {
            return {
                tabIndex: 0,
                updateValues: {},
                formEditField: {},
                show_assigned_recorders: false,
                form: {
                    name: null,
                    alternate_name: null,
                    number: null,
                    comment: null,
                    recorder_id: null,
                },
            };
        },
        methods: {
            saveCommand() {
                this.$parent.$data.isLoading = true;
                commandRepository.createCommand(this.form)
                    .then(() => {
                        this.$store.dispatch('loadCommands')
                            .then(() => {
                                this.$parent.$data.isLoading = false;
                                this.tabIndex = 0;
                            });
                    }).catch((msg) => {
                    this.showErrorMessage('Could not safe command!');
                    this.$log.warn(msg);
                });
            },
            initCommandUpdate(command, fieldName) {
                this.$set(this.formEditField, command.id + '_' + fieldName, true);
                this.$set(this.updateValues, command.id + '_' + fieldName, command[fieldName]);
            },
            updateCommand(id, fieldName) {
                this.$parent.$data.isLoading = true;
                const data = {};
                data[fieldName] = this.updateValues[id + '_' + fieldName];
                commandRepository.updateCommand(id, data)
                    .then(() => {
                        this.$store.dispatch('loadCommands')
                            .then(() => {
                                this.$parent.$data.isLoading = false;
                                this.formEditField[id + '_' + fieldName] = false;
                            });
                    });
            },
            deleteCommand(id) {
                this.$parent.$data.isLoading = true;
                commandRepository.deleteCommand(id)
                    .then(() => {
                        this.$store.dispatch('loadCommands')
                            .then(() => {
                                this.$parent.$data.isLoading = false;
                            });
                    });
            },
            initRecCommandUpdate(command, fieldName) {
                this.$set(this.formEditField, command.id + '_' + fieldName, true);
                this.$set(this.updateValues, command.id + '_' + fieldName, command[fieldName]);
            },
            updateRecCommand(id, fieldName) {
                this.$parent.$data.isLoading = true;
                const data = {};
                data[fieldName] = this.updateValues[id + '_' + fieldName];
                recorderRepository.updateRecorderCommand(id, data)
                    .then(() => {
                        this.$store.dispatch('loadRecorderCommands')
                            .then(() => {
                                this.$parent.$data.isLoading = false;
                                this.formEditField[id + '_' + fieldName] = 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('loadCommands')
                .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'},
                    ],
                };
            },
            commands() {
                return this.$store.state.recorderCommands;
            },
            recorders() {
                return this.$store.state.recorders;
            },
        },
    };
</script>

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

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

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