import React, { Component } from "react";
import { View } from "react-native";
import { getReactions, getUserPreview } from "../helper";
import { Reaction } from "./Reaction";

class Reactions extends Component {
	state = {
		reactions: getReactions(),
	};

	getReaction(key) {
		if (!this.props.entity) {
			return {};
		}
		if (!this.props.entity.Reactions) {
			this.props.entity.Reactions = {};
		}
		return this.props.entity.Reactions[key] || {};
	}

	onLike(key) {
		if (!this.props.entity.Reactions) {
			this.props.entity.Reactions = {};
		}
		if (!this.props.entity.Reactions[key]) {
			this.props.entity.Reactions[key] = {};
		}
		this.props.entity.Reactions[key][this.props.user.uid] = getUserPreview(
			this.props.user,
		);
		this.props.onUpdateReactions();
	}

	onUnlike(key) {
		if (!this.props.entity.Reactions) {
			return;
		}
		if (!this.props.entity.Reactions[key]) {
			return;
		}
		delete this.props.entity.Reactions[key][this.props.user.uid];
		this.props.onUpdateReactions();
	}

	render() {
		return (
			<View style={[styles.container, this.props.style]}>
				{this.state.reactions.map((r, i) => {
					return (
						<Reaction
							key={i}
							reaction={r}
							entityType={this.props.entityType}
							entityId={this.props.entityId}
							reactions={this.getReaction(r.key)}
							anyHighlighted={this.props.anyHighlighted}
							userId={this.props.user.uid}
							onLike={this.onLike.bind(this, r.key)}
							onUnlike={this.onUnlike.bind(this, r.key)}
							site={this.props.site}
						/>
					);
				})}
			</View>
		);
	}
}

const styles = {
	container: {
		flexDirection: "row",
		justifyContent: "center",
		width: "100%",
	},
};

export { Reactions };
