import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TimeAgo from "javascript-time-ago";
import * as moment from "moment/min/moment-with-locales.min";
import nl from "javascript-time-ago/locale/nl";
const randomColor = require('randomcolor');
const Color = require('color');
import {Text, View, Image} from 'react-native';

export default class Avatar extends Component {
    timeAgo = null;

    constructor(props) {
        super(props);
        TimeAgo.addLocale(nl);
        moment.locale("nl");
        this.timeAgo = new TimeAgo('nl');
    }

    getBestTextColor(color) {
        return Color(color).isLight() ? '#111' : '#fff';
    }

    getRandomColor(name, id) {
        return randomColor({
            luminosity: 'dark',
            hue: "blue",
            seed: name + id
        });
    }

    getInitials(name) {
        const initials = name.match(/\b\w/g) || [];
        return ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
    }

    render() {
        const {message} = this.props;

        const avatarColor = this.getRandomColor(message.sender.name, message.sender.id);
        const hasLogo = message.sender.logo !== null && message.sender.logo !== undefined;

        let avatar = <View style={{width: 30, height: 30, padding: 5, paddingLeft: 6, borderRadius: 15, backgroundColor: avatarColor}}>
            <Text style={{color: this.getBestTextColor(avatarColor)}}>
                {this.getInitials(message.sender.name)}
            </Text></View>;
        if (hasLogo) {
            avatar = <View style={{width: 30, height: 30, borderRadius: 15, backgroundColor: "white"}}>
                <Image style={{width: 30, height: 30, borderRadius: 15}} source={{uri: message.sender.logo}} />
            </View>;
        }

        return avatar;
    }
}

Avatar.propTypes = {
    message: PropTypes.object
};
