/** Pure component for each Event Item **/
import firebase from 'firebase';
import React from 'react';
import { Dimensions, Image, Text, TouchableOpacity, View } from 'react-native';
import { Card, Icon } from 'react-native-elements';
import { GOING, NOT_GOING } from '../../components/AttendeeStatusTypes';
import colors from '../../config/colors.json';
import { strings } from '../../locales/i18n';

const TEMP_IMAGE = require('../../../assets/tagfer_brand_and_logo_512.png');

const SCREEN_WIDTH = Dimensions.get('window').width;

let attendeesResult = {};
let attendees = [];

class EventItem extends React.PureComponent {
  /**
  * Component Will Mount
  **/
  async componentWillMount() {
    attendeesResult = await firebase.database().ref(`/eventAttendees/${this.props.item.uid}`).once('value');
    attendeesResult = JSON.parse(JSON.stringify(attendeesResult));

    if (attendeesResult === null || (Object.keys(attendeesResult).length === 0 && attendeesResult.constructor === Object)) {
      return;
    }
    // If there are attendees we need to force a rerender since it doesn't happen on a pure component
    this.forceUpdate();
  }

  /**
  * Renders the main image for an event
  **/
  renderEventImage(item) {
    if (item.eventMainImg) {
      return (
        <Image
          source={{ uri: item.eventMainImg }}
          style={styles.eventImageStyle}
        />
      );
    }
    return (
      <Image
        source={TEMP_IMAGE}
        style={styles.eventImageStyle}
      />
    );
  }

  /**
  * Renders attendees avatars on each event
  **/
  renderEventAttendees() {
    if (attendeesResult === null || (Object.keys(attendeesResult).length === 0 && attendeesResult.constructor === Object)) {
      return <Text>0 </Text>;
    }

    attendees = [];

    for (const property in attendeesResult) {
      if (attendeesResult[property].status === GOING) {
        attendees.push(attendeesResult[property]);
      }
    }

    if (attendees.length === 0) {
      return <Text>0 </Text>;
    }

    return attendees.map((attendee) => {
      if (attendee.profile.profileAvatarImg) {
        return (
          <Image
            key={attendee.uid}
            source={{ uri: attendee.profile.profileAvatarImg }}
            style={styles.avatarImageStyle}
          />
        );
      }
      return (
        <Icon
          key={attendee.uid}
          name='account-circle'
          size={35}
          color={colors.lightTeal}
          containerStyle={{ marginBottom: 5 }}
        />
      );
    });
  }

  /**
  * Renders the attendee status section
  **/
  renderAttendeeStatus(status, profileName) {
    if (status === GOING) {
      return (
        <View style={{ flex: 1 }}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
            <Icon
              name={'ios-checkmark-circle'}
              type="ionicon"
              size={30}
              color={colors.green}
              containerStyle={styles.iconStyle}
            />
            <Text style={{ fontSize: 15, fontWeight: 'bold', color: colors.green }}>{status}</Text>
          </View>
          <Text style={{ fontSize: 15, fontWeight: 'bold', alignSelf: 'center', marginBottom: 5, color: colors.buttonBlue }}>{profileName}</Text>
        </View>
      );
    } else if (status === NOT_GOING) {
      return (
        <View style={{ flex: 1 }}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
            <Icon
              name={'ios-checkmark-circle'}
              type="ionicon"
              size={30}
              color={colors.red}
              containerStyle={styles.iconStyle}
            />
            <Text style={{ fontSize: 15, fontWeight: 'bold', color: colors.red }}>{status}</Text>
          </View>
        </View>
      );
    }
      return (
        <View style={{ flex: 1 }}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
            <Icon
              name={'ios-checkmark-circle'}
              type="ionicon"
              size={30}
              color={colors.orange}
              containerStyle={styles.iconStyle}
            />
            <Text style={{ fontSize: 15, fontWeight: 'bold', color: colors.orange }}>{status}</Text>
          </View>
          <Text style={{ fontSize: 15, fontWeight: 'bold', alignSelf: 'center', marginBottom: 5, color: colors.buttonBlue }}>{profileName}</Text>
        </View>
      );
  }

  /**
  * Render method
  **/
    render() {
      const item = this.props.item;
      const {
        eventName,
        hostProfile,
        endTime,
        eventLocation,
        eventTimeZone,
        startDate,
        startTime,
        uid
      } = item;

      const formattedStartTime = `${startTime.substr(0, 4)}${startTime.substr(7, startTime.length)}`;
      const formattedEndTime = `${endTime.substr(0, 4)}${endTime.substr(7, endTime.length)}`;


      let status = NOT_GOING;
      let profileName = '';
      if (this.props.myAttendeeStatus.length > 0) {
        for (let i = 0; i < this.props.myAttendeeStatus.length; i++) {
          if (this.props.myAttendeeStatus[i].uid === item.uid) {
            status = this.props.myAttendeeStatus[i].status;
            profileName = this.props.myAttendeeStatus[i].profile.profileName;
          }
        }
      }

      return (
      <Card containerStyle={{ padding: 0, marginHorizontal: 5 }}>
        <TouchableOpacity
          style={styles.eventContainer}
          onPress={() => this.props.navigation.navigate('eventDetailsScreen', { item, myAttendeeStatus: this.props.myAttendeeStatus })}
        >
          {this.renderEventImage(item)}

          <View style={{ width: SCREEN_WIDTH * 0.5 }}>
            <Text style={styles.eventTitleStyle}>{eventName}</Text>
            <Text style={styles.eventMiddleText}>{startDate}</Text>
            <Text style={[styles.eventMiddleText, { fontSize: 12 }]}>{formattedStartTime} - {formattedEndTime} {eventTimeZone}</Text>
            <Text style={styles.eventMiddleText}>{eventLocation}</Text>
            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              {this.renderEventAttendees()}
              <Text style={styles.eventSmallText}>{strings('event.homeScreen.areGoing_label')}</Text>
            </View>
          </View>
        </TouchableOpacity>

        <View style={styles.eventActionButtonsContainer}>
          {this.renderAttendeeStatus(status, profileName)}

          <TouchableOpacity
            style={styles.shareEventContainer}
            onPress={() => {
              this.props.navigation.navigate('shareEventQRCodeScreen', { eventName, eventLocation, hostTagferId: hostProfile.tagferId, startDate, startTime: formattedStartTime, endTime: formattedEndTime, uid });
            }}
          >
            <Icon
              name={'action-redo'}
              type="simple-line-icon"
              size={30}
              color={colors.buttonBlue}
              containerStyle={styles.iconStyle}
            />
          </TouchableOpacity>
        </View>
      </Card>
    );
  }
}

const styles = {
  eventContainer: {
    flex: 1,
    flexDirection: 'row',
    width: '100%'
  },
  eventImageStyle: {
    width: SCREEN_WIDTH / 3,
    height: '100%',
    marginRight: 5,
    resizeMode: 'contain'
  },
  eventTitleStyle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginVertical: 5
  },
  eventMiddleText: {
    fontSize: 15,
    marginBottom: 5
  },
  eventSmallText: {
    fontSize: 12
  },
  eventActionButtonsContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    borderTopWidth: 1,
    borderColor: colors.lightGrey,
  },
  shareEventContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderLeftWidth: 1,
    borderColor: colors.lightGrey
  },
  iconStyle: {
    marginLeft: 20,
    marginRight: 5,
  },
  shareButtonStyle: {
    fontSize: 18
  },
  avatarImageStyle: {
    width: 30,
    height: 30,
    borderRadius: 15,
    marginBottom: 5,
    marginRight: 5
  }
};

export default EventItem;
