/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  ListView,
  Text,
  View,
  Image,
  TouchableOpacity,
  AlertIOS,
  ActivityIndicatorIOS,
  RefreshControl,
} from 'react-native';

import InfoPage from './Info.js'
var REQUEST_URL = 'http://127.0.0.1:3000/users/list';
var MOCKED_MOVIES_DATA = [
  {title: 'Title', year: '2015', posters: {thumbnail: 'http://i.imgur.com/UePbdph.jpg'}},
];

var page = 1;
var dataSource = [];
const shareImg = 'data:image/png;base64, ';

var home = React.createClass({
getInitialState: function() {
    return {
      isRefreshingArticles: false,
      isLoading: false,
      loaded:false,
      loadFail:false,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      filter: '',
      queryNumber: 0,
    };
  },

  componentDidMount:function(){
    console.log('componentDidMount');
          this.props.navComponent.setNavItems({
      title: {
        component: (
          <Text style={styles.title}>
          首页
          </Text>
        ),
        event: function() {
          page = 1;
          this.fetchData();
        }.bind(this)
      }
    }),
    this.fetchData();
  },

  onEndReached:function() {
    // if (home1.state.isLoading) {
    //   return;
    // };
    // home1.setState({isLoading:true});
    console.log('reach');

    page++;
    this.fetchData();
  },
  onRefreshData:function(){

    this.setState({
                isRefreshingArticles: true,
              });
    console.log('onRefreshData:');
    // dataSource = [];
    page = 1;
    
    return this.fetchData();
  },
//数据查询.
  fetchData:function(){
    var url = REQUEST_URL + '?page=' + page;
    return fetch(url)
        .then((response) => response.json())
        .catch((error) => {
          AlertIOS.alert('没有数据');
                    this.setState({
            loaded: false,
            loadFail: true,
          });
        })
        .then((responseData) => {
          this.setState({
                isRefreshingArticles: false,
              });
          if(responseData){
            var movieArr = dataSource;
            for (var i in responseData.datas) {
              movieArr.push(responseData.datas[i]);
            };
            if(page === 1){
              dataSource = responseData.datas;
            }
              this.setState({
              dataSource: this.state.dataSource.cloneWithRows(dataSource),
              loaded: true,
              loadFail: false,
            });
          }else{
            this.setState({
                loaded: false,
                loadFail: false,
              });
          }
          
        })
        .done();
  },
  pushInfo:function(index){
    console.log(this.state.dataSource.getRowData(0,index))

    this.props.navigator.push({
      title: 'New Page',
      component: <InfoPage movie={this.state.dataSource.getRowData(0,index)}> </InfoPage>
    });
  },

 render:function(){
  // return this.renderLoadingView();
  
    if (!this.state.loaded) {
      return this.renderLoadingView();
    }

return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={this.renderMovie}
        renderSeparator={this.renderMovieRow}
        onEndReached={this.onEndReached}
        refreshControl={
          <RefreshControl
            refreshing={this.state.isLoading}
            onRefresh={this.fetchData}
            tintColor="#61BFA9"
            title="刷新"
            colors={['#ff0000', '#00ff00', '#0000ff']}
            progressBackgroundColor="#61BFA9"/>}
        style={styles.listView}/>
    );
},
  renderFoot:function(){
    return (
      <View style={styles.foot}>
      <ActivityIndicatorIOS />
      <Text>下拉刷新</Text>
      </View>
    );
  },
  renderHeaderWrapper:function(refreshingIndicator) {
    return (
      <View>
        <Text>My custom header</Text>
        {/*  you MUST render the refreshingIndicator (which is passed in as the first argument) */}
        {refreshingIndicator}
      </View>
    )
  },
  renderLoadingView:function(){
    let stateStr = '正在刷新';
    if (this.state.loadFail) {stateStr = '点击刷新'};
    return (
      <TouchableOpacity onPress={() =>this.fetchData()} style={styles.container} >
      <View style={styles.container}>
        <Text>
          {stateStr}
        </Text>
        <ActivityIndicatorIOS />
      </View>
      </TouchableOpacity>
    );
  },
  renderMovieRow:function(sectionID, rowID, adjacentRowHighlighted){
        return (
      <View style={styles.topContainer} key={rowID}>

      </View>
    );
  },

 renderMovie:function(movie,sectionID, rowID, highlightRow){
    return (
      
      <View style={styles.container} key={rowID}>
      <TouchableOpacity onPress={() =>this.pushInfo(rowID)} style={styles.container} >
        <Image
          source={{uri: movie.imageurl}}
          style={styles.thumbnail}/>
        <View style={styles.rightContainer}>
          <Text style={styles.title}>{movie.title}</Text>
        </View>
        </TouchableOpacity>
      </View>
    );
  }
});

const styles = StyleSheet.create({
   container: {
    flex:2,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'White',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  shoucan: {
    textAlign: 'left'
  },
  tophead:{
    height : 30,
    paddingTop: -30,
    textAlign:'center',
    backgroundColor:'red',

  },
  foot: {
    height : 40,
    alignItems:'center',
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  title: {
    fontSize: 15,
    marginBottom: 8,
    marginTop: 10,
    marginLeft: 4,
    marginRight: 4,
    textAlign: 'left',
    borderWidth: 0,
    borderColor: '#333333',
  },
  year: {
    textAlign: 'center',
  },
  rightContainer: {
    flex: 1,
  },
  topContainer:{
    flex:1,
    height : 20,
    backgroundColor: 'LightGray',
  },
   thumbnail: {
    width: 400,
    height: 200,
  },
    listView: {
    paddingTop: 0,
    marginBottom: 44,
    backgroundColor: 'LightGray',
  },
    navItem: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
});

module.exports = home;
