<script>
    import Avatar from "../account/Avatar.svelte";
    import {fly} from "svelte/transition";
    import {createEventDispatcher} from "svelte";
    import Dropdown from "../common/Dropdown.svelte";

    const dispatch = createEventDispatcher();
    export let member;
    export let roles;


    function removeFrom(e, aRole) {
        e.preventDefault();
        let newRoles = member.roles.filter((r) => r !== aRole);
        dispatch("update", {
            user: member.id,
            roles: newRoles,
        });
    }

    function addTo(e, aRole) {
        e.preventDefault();

        let newRoles = [...member.roles, aRole];
        console.log(member.roles)
        console.log(aRole)
        console.log(newRoles)
        dispatch("update", {
            user: member.id,
            roles: newRoles,
        });
    }


</script>

<div
        transition:fly={{ duration: 200 }}
        class="member-item"
>
    <div class="member-name status-{member.roles.includes('removed')  ? 'removed' : 'active'}">
        <Avatar name={member.name ?? "" } side={32}/>
        <div>
            <div>
                {member.name}
            </div>
            <div>
                {member.email}
            </div>
        </div>
    </div>
    <Dropdown orientation="right">
        <div slot="button">
            Roles
        </div>
        <h6 class="dropdown-header">Remove role</h6>
        {#each roles as role}
            {#if member.roles.includes(role)}
                <button
                        class="dropdown-item button"
                        on:click={(e) => removeFrom(e,role)}
                >
                    {role}
                </button>
            {/if}
        {/each}


        <h6 class="dropdown-header">Add role</h6>
        {#each roles as role}
            {#if !member.roles.includes(role)}
                <button
                        class="dropdown-item button"
                        on:click={(e) => addTo(e,role)}
                >
                    {role}
                </button>
            {/if}
        {/each}

    </Dropdown>

</div>
<style>
    .status-removed {
        opacity: .5;
    }


</style>
