import { List } from 'immutable';
import React, { Component } from 'react';
import PropTypes from 'prop-types';

import { ActivityIndicator, FlatList, StyleSheet, View } from 'react-native';

import EventListItem from '../components/Events/EventListItem.container.js';

export default class Events extends Component {
    static get propTypes() {
        return {
            events: PropTypes.oneOfType([PropTypes.array, PropTypes.instanceOf(List)]),
            fetchEvents: PropTypes.func.isRequired,
            setActiveEvent: PropTypes.func.isRequired,
        };
    }

    static get defaultProps() {
        return {
            events: [],
        };
    }

    constructor(props) {
        super(props);
        this._renderEventListItem = this._renderEventListItem.bind(this);
        this._setActiveEvent = this.setActiveEvent.bind(this);
    }

    setActiveEvent(eventId) {
        this.props.setActiveEvent(eventId);
    }

    _keyExtractor = (event, index) => `${event.id}_${index}`;

    _renderEventListItem({ event }) {
        return <EventListItem event={event} setActiveEvent={this.setActiveEvent} />;
    };

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

        return (
            <View style={styles.container}>
                {events.size > 0 ? (
                    <FlatList
                        data={events}
                        keyExtractor={this._keyExtractor}
                        renderItem={this._renderEventListItem}
                        contentContainerStyle={styles.eventListContentContainer}
                        style={styles.eventList}
                    />
                ) : (
                    <ActivityIndicator animating={true} size="large" />
                )}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    eventListContentContainer: {
        alignItems: 'stretch',
        justifyContent: 'flex-start',
    },
});
