<template>
    <div>
        <credential-form-modal modal-id="newCredentialModal" :descriptions="creddescList" :create="true" :pcid="pcid"></credential-form-modal>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#newCredentialModal">New Credential</button>
        <div v-for="credential in credentials" :key="credential.credid">
            <credential :credential="credential" :descriptions="creddescList"></credential>
        </div>
    </div>
</template>
<script>
import Credential from '../components/Credential.vue'
import CredentialFormModal from '../components/CredentialFormModal.vue'
export default {
    components: {
        Credential,
        CredentialFormModal,
    },
    props: {
        credentials: {
            type: Array,
            required: true
        },
        descriptions: {
            type: Array,
            required: true
        },
        pcid: {
            type: Number
        },
        groupid: {
            type: Number
        }
    },
    computed : {
        creddescList: function () {
            let list = {}
            this.descriptions.map(val => {
                list[val.creddescid] = val.credtitle
            })
            return list
        }
    },
    methods: {
        deleteCred: function(index) {
            this.credentials.splice(index, 1);
        }
    },
    mounted () {
        if (this.pcid) {
            Echo.channel('credlist.pcid.'+this.pcid)
                .listen('CredentialDeleted', (e) => {
                    let deletedCred = e.credential
                    let index = this.credentials.findIndex((credential) => {
                        return credential.credid === deletedCred['credid']
                    })
                    $('#credential'+deletedCred['credid']+'deleteModal').modal('hide');
                    this.deleteCred(index);
                })
                .listen('CredentialAdded', (e) => {
                    this.credentials.unshift(e.credential)
                })
        }
        if (this.groupid) {
            Echo.channel('credlist.groupid.'+this.groupid)
                .listen('CredentialDeleted', (e) => {
                    let deletedCred = e.credential
                    let index = this.credentials.findIndex((credential) => {
                        return credential.groupid === deletedCred['groupid']
                    })
                    $('#credential'+deletedCred['credid']+'deleteModal').modal('hide');
                    this.deleteCred(index);
                })
                .listen('CredentialAdded', (e) => {
                    this.credentials.unshift(e.credential)
                })
        }
    }
}
</script>