import React, { Component } from 'react';
import {
  CameraRoll,
  ScrollView,
  TouchableOpacity,
  Text,
  View,
  StyleSheet,
} from 'react-native';
import { queryResourceByUsage } from '../../services/resource';
import config from '../../utils/config';
import { getToken } from '../../utils/auth';
import { errors } from '../../utils/error';
import { encrypt } from '../../utils/helper';

const EXAMPLES = [
  {
    title: '全部',
    description: '所有分类，所有tag',
    startOnGrid: true,
    displayNavArrows: true,
    displayActionButton: true,
  },
];
// fill 'Library photos' example with local media
CameraRoll.getPhotos({
  first: 30,
  assetType: 'Photos',
})
  .then((data) => {
    const media = [];
    data.edges.forEach(d =>
      media.push({
        photo: d.node.image.uri,
      }));
    EXAMPLES[0].media = media;
  })
  .catch(error => console.info(error));

export default class HomeScreen extends Component {
  constructor(props) {
    super(props);
    // 获取所有tag 类型下面的照片放到Examples里面
    queryResourceByUsage(this.props.navigation.state.params.usage)
      .then((data) => {
        const media = [];
        // 请求Token
        let strtoken = '';
        getToken()
          .then((token) => {
            if (!token) {
              return Promise.reject(errors.tokenMissing());
            }
            strtoken = encrypt(token);
            data.forEach((d) => {
              media.push({
                photo: `${config.apiContextPath}/resource/${encodeURIComponent(strtoken)}/${encodeURIComponent(d)}`,
              });
              console.info(`${config.apiContextPath}/resource/${encodeURIComponent(strtoken)}/${encodeURIComponent(d)}`);
            });
            EXAMPLES[0].media = media;
          })
          .catch(error => console.info(error));
      })
      .catch(err => console.info(err));
  }
  renderExampleRow = (example) => {
    const { navigate } = this.props.navigation;
    const { title, description } = example;

    return (
      <TouchableOpacity
        key={`example_${title}`}
        onPress={() => {
          navigate('PhotoViewDetail', {
            example,
          });
        }}
      >
        <View style={styles.row}>
          <Text style={styles.rowTitle}>
            {title}
          </Text>
          <Text style={styles.rowDescription}>
            {description}
          </Text>
        </View>
      </TouchableOpacity>
    );
  };

  render() {
    return (
      <ScrollView style={styles.container}>
        {EXAMPLES.map(this.renderExampleRow)}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  list: {
    flex: 1,
    paddingTop: 54,
    paddingLeft: 16,
  },
  row: {
    flex: 1,
    padding: 8,
    borderBottomColor: 'rgba(0, 0, 0, 0.1)',
    borderBottomWidth: 1,
  },
  rowTitle: {
    fontSize: 14,
  },
  rowDescription: {
    fontSize: 12,
  },
});
