import React, { Component } from 'react';
import { ListView } from 'react-native';
import { connect } from 'react-redux';
import { View } from 'native-base';
import { appointmentFetch, appointmentDelete } from './../actions'
import AppointmentListItem from './../components/AppointmentListItem'

import realm from './../Database'

class AppointmentList extends Component {

    componentWillMount() {
        this.props.appointmentFetch()
        this.createDataSource(this.props)
    }

    componentWillReceiveProps(nextProps) {
        // nextProps are the next set of props that this component
        // will be rendered with
        // this.props is still the old set of props
        this.createDataSource(nextProps);
    }

    createDataSource({ appointments }) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });

        this.dataSource = ds.cloneWithRows(appointments.appointments);
    }

    renderRow({ id, doctorName, date, time, place }) {
        let appointment = { id, doctorName, date: date.toString(), time, place }
        return <AppointmentListItem data={appointment} />
    }

    render() {
        return (
            <View>
                <ListView
                    enableEmptySections
                    dataSource={this.dataSource}
                    renderRow={this.renderRow}
                />
            </View>
        )
    }

}

const mapStateToProps = state => {
    return { appointments: state.appointments }
};

export default connect(mapStateToProps, { appointmentFetch, appointmentDelete })(AppointmentList);