<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>
export default {
    props: {
        credentialList: {
            type: Array,
            required: true
        },
        descriptions: {
            type: Array,
            required: true
        },
        pcid: {
            type: Number
        },
        groupid: {
            type: Number
        }
    },
    data () {
        return {
            credentials: this.credentialList
        }
    },
    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.pcid === deletedCred['pcid']
                    })
                    $('#credential'+deletedCred['credid']+'deleteModal').modal('hide');
                    this.deleteCred(index);
                })
        }
        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);
                })
        }
    }
}
</script>