/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require("react-native");

var {
  AppRegistry,
  StyleSheet,
  View,
  Text,
  ListView,
  WebView
} = React;


var REDDIT_URL = "http://www.reddit.com/.json";


var AwesomeProject = React.createClass({

  getInitialState : function(){
    return {
      dataSource : new ListView.DataSource({
        rowHasChanged : (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  },

  componentDidMount : function(){
    this.fetchData();
  },

  fetchData : function(){
    fetch(REDDIT_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          dataSource : this.state.dataSource.cloneWithRows(
            responseData.data.children
          ),
          loaded : true,
        });
      }).done();
  },

  render : function(){
    if (!this.state.loaded){
      return this.renderLoadingView();
    }else{
      return (
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderPost}
          style={styles.listView}
        />
      );
    }
  },

  renderLoadingView: function(){
    return (
      <View style={styles.container}>
        <Text>Loading...</Text>
      </View>
    );
  },

  renderPost: function(post){
    return (
      <View style={styles.post}>
        <Text style={styles.score}>{post.data.score}</Text>
        <Text
          style={styles.title}
          onPress={this.setPage}>
            {post.data.title}
        </Text>
      </View>
    );
  },
});

var styles = StyleSheet.create({
  container : {
    flex: 1,
    backgroundColor: '#ecf0f1',
  },
  post : {
    flex : 1,
    flexDirection : "row",
    backgroundColor : "#ecf0f1",
    marginBottom: 10
  },
  title : {
    fontSize : 20,
    flex : 8,
    color : "#3498db"
  },

  listView : {
    backgroundColor: '#ecf0f1',
  },

  score : {
    flex : 1,
    color : "#2ecc71",
    alignSelf : "center"
  },

});

AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
