<template>
    <modal :id="id" tabindex="-1" role="dialog" :aria-labelledby="id+'Label'">
        <h5 slot="header" class="modal-title" :id="id+'Label'">
            Edit Credential
        </h5>
        <div slot="body">
            <div class="form-group">
                <label for="newusername">Username</label>
                <input type="text" :name="'newusername'+data.credid" :id="'newusername'+data.credid" class="form-control credential" v-model="data.creduser">
            </div>
            <div class="form-group">
                <label for="newpassword">Password</label>
                <input type="text" :name="'newpassword'+data.credid" :id="'newpassword'+data.credid" class="form-control credential" v-model="data.credpass">
                <button type="button" class="btn btn-secondary" @click="getRandomPassword(data.credid)">Generate Random</button>
            </div>
            <div class="form-group"></div>
        </div>
        <div slot="footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" @click="updateCredential()">Save</button>
        </div>
    </modal>
</template>
<script>
export default {
    props: ['populateWith', 'modalId'],
    data() {
        return {
            data: JSON.parse(JSON.stringify(this.populateWith)),
            id: this.modalId,
            errors: []
        }
    },
    methods: {
        rndStr(len) {
            let text = ""
            let chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%"
        
            for( let i=0; i < len; i++ ) {
                text += chars.charAt(Math.floor(Math.random() * chars.length))
            }
            return text
        },
        getRandomPassword(id) {
            this.data.credpass = this.rndStr(16);
        },
        updateCredential() {
            axios.put('/api/credentials/' + this.data.credid, this.data).then(response => {}).catch(error =>{console.error(error)});
            $('#credential'+this.data.credid+'editModal').modal('hide');
        }
    }
    
}
</script>