import React, { FunctionComponent } from "react";
import { View, StyleSheet } from "react-native";
import { Avatar, Badge, IconButton } from "react-native-paper";
import {  Presence } from "../../store/contacts/types";
import { IPeer } from "../../store/peer/types";
import { PresenceView as PresenceIcon } from './PresenceView';

interface IProps {
    peer: IPeer;
    avatarSize?: number;
    presenceIconSize?: number;
    presence: Presence;
}

export const AvatarPresenceBadge: FunctionComponent<IProps> = ({ presence, peer, presenceIconSize = 16, avatarSize = 50 }) => {
    const { nameInitials, imageURL, name } = peer;

    const setAvatarBgColor = (name: string) => {
        const textAvatarColors: string[] = [
            '#ca8741', '#e44647', '#c62582', '#9b4ce7', '#6573ee',
            '#1b70e0', '#6ec7d9', '#98d1b1', '#7fbd40', '#b2d334',
            '#dcd232', '#f1be00'
        ];
        if (name){
            const upperCaseDisplayName = name.toUpperCase();
            let sum: number = 0;
            for (let charCtr = 0; charCtr < upperCaseDisplayName.length; charCtr++) {
                sum += upperCaseDisplayName.charCodeAt(charCtr);
            }
            return textAvatarColors[sum % textAvatarColors.length];

        } 
        return '#bcbcbc';
      
    };
    return (
        <View style={styles.avatarContainer}>
            {imageURL ? (
                <Avatar.Image source={{ uri: imageURL }} size={avatarSize} style={{ backgroundColor: setAvatarBgColor(name) }} />
            ) : (
                <Avatar.Text label={nameInitials} size={avatarSize} style={{ backgroundColor: setAvatarBgColor(name) }} />
            )}
           <PresenceIcon presence={presence} size={presenceIconSize} style={styles.presenceBadge}/>

        </View>
    );
};

const styles = StyleSheet.create({
    avatarContainer: {
        position: 'relative',
    },
    presenceBadge: {
        position: 'absolute',
        bottom: 0,
        right: 0,
        borderRadius: 9999,
    },
    dndIcon: {
        backgroundColor: '#F44336',
        margin: 0,
        padding: 0,
    },
});