import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Image,
  FlatList,
  Alert,
  ScrollView,
} from 'react-native';
import ViewShot from 'react-native-view-shot';
import axios from 'axios';
import api from '../../services/api';
import RNImageToPdf from 'react-native-image-to-pdf';
import FastImage from 'react-native-fast-image';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import history from '../../common/history';
import moment from 'moment';
import LoadingView from '../../common/loading';
import NaviBar from '../../components/navi-bar';
import CameraRoll from '@react-native-community/cameraroll';
import BackHeader from '../../components/backHeader';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import Migrations from '../../services/realm/Mirgrations';
import {inject, observer} from 'mobx-react';
import {queryUser} from '../../services/realm/realmManger';
//import Swiper from 'react-native-swiper'
import Global from '../../services/Global';
import {width, height} from '../../common/screen';
import AddFunction from '../../common/addFunction';
import NewsList from './newsList';
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../../services/realm/schemeas';
import * as rssParser from 'react-native-rss-parser';

import Realm from 'realm';
import {observable} from 'mobx';
import {func} from 'prop-types';
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
@inject('appStore')
@observer
export default class News extends Component<Props> {
  @observable
  news = [];
  @observable
  date = '';

  constructor(props) {
    super(props);
    this.store = props.appStore;
  }
  componentWillMount() {
    this.getRentChatNews();
    // this.loadNews();
    this.props.navigation.setParams({
      handleThis: this.store.text.new,
    });
  }
  // static navigationOptions = inject("appStore")(observer(({appStore, otherProp}) => {
  //   return {
  //     tabBarLabel:   otherProp.appStore.text.new
  //   }}));

  // static navigationOptions = {
  //   tabBarLabel: 'Home!',
  // };

  // static navigationOptions = () => {
  //   return {
  //     tabBarLabel:  'fff'
  //   }}
  static navigationOptions = ({navigation}) => {
    const {params = {}} = navigation.state;
    return {
      tabBarLabel: params.handleThis,
    };
  };

  async getRentChatNews() {
    this.news = [];
    this.store.loading = true;
    try {
      const response = await axios.get(api.getNews, {
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      });

      console.log(response);
      await this.rentChatNewsHandler(response.data.content);
      await this.loadNews();

      this.store.loading = false;
    } catch (error) {
      this.store.loading = false;
      console.log(error);
    }
  }

  async loadNews() {
    try {
      this.store.loading = true;
      await fetch(
        'https://www.news.gov.hk/tc/categories/finance/html/articlelist.rss.xml',
      )
        .then(response => response.text())
        .then(responseData => rssParser.parse(responseData))
        .then(rss => {
          console.log(rss);
          this.date = rss.lastUpdated.substring(0, 26);
          console.log(this.date);
          console.log(rss.items.length);
          this.newsHandler(rss.items, this.date);
          this.store.loading = false;
        });
    } catch (e) {
      this.store.loading = false;
      console.log(e);
    }
  }
  async myAsyncPDFFunction(uri) {
    var data = [uri];
    try {
      const options = {
        imagePaths: data,
        name: 'testing',
      };
      const pdf = await RNImageToPdf.createPDFbyImages(options);

      console.log(pdf.filePath);
    } catch (e) {
      console.log(e);
    }
  }

  async rentChatNewsHandler(data) {
    this.news = [];
    var newsArray = [];
    await data.map((news, index) => {
      if (news.status) {
        var items = {};
        items.type = 'rentchat';
        items.id = news.id;
        items.image = news.image;
        items.title = news.title;
        items.description = news.content;
        items.date = moment(news.date, 'YYYY-MM-DD').format(
          'ddd, DD, MMM, YYYY, hh:mm:ss',
        );
        newsArray.push(items);
      }
    });
    this.news = newsArray;
  }

  async newsHandler(data, date) {
    var newsArray = [];
    await data.map((news, index) => {
      var items = {};
      items.type = 'hknews';
      items.id = index;
      items.image = news.description.slice(
        10,
        news.description.indexOf('"/><p><p>'),
      );
      items.title = news.title;
      items.description = news.description;
      items.date = date;
      newsArray.push(items);
    });
    this.news = this.news.concat(newsArray);
  }

  cloneDeep(item) {
    var data = {};
    data.id = item.id;
    data.image = item.image;
    data.description = item.description;
    data.title = item.title;
    data.copyright = item.copyright;
    return data;
  }

  onCapture = uri => {
    console.log('do something with ', uri);
  };

  render() {
    return (
      <View style={styles.container}>
        <LoadingView visible={this.store.loading} />
        <BackHeader title={this.store.text.new} back={true} instance={this} />
        <ScrollView>
          <ViewShot
            ref="viewShot"
            options={{format: 'jpg', quality: 0.9}}
            captureMode="mount">
            {this.news.length > 0 ? (
              <TouchableOpacity
                style={{
                  borderBottomColor: colors.line2Color,
                  borderBottomWidth: 1,
                  width: width,
                }}
                onPress={() => {
                  history.push(this, '/newsDetails', {
                    details: this.cloneDeep(this.news[0]),
                    type: this.news[0].type,
                  });
                }}>
                <Image
                  style={{width: width, height: 200}}
                  source={{
                    uri: this.news[0].image,
                  }}
                />
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    fontSize: 17,
                    margin: 10,
                  }}>
                  {this.news[0].title}
                </Text>
                <Text
                  style={{
                    fontFamily: Fonts.ubuntu,
                    fontSize: 14,
                    marginLeft: 10,
                    marginBottom: 5,
                    color: colors.textColor,
                  }}>
                  {this.news[0].date}
                </Text>
              </TouchableOpacity>
            ) : (
              <View></View>
            )}

            <FlatList
              collapsable={false}
              data={this.news}
              renderItem={({item}) => (
                <NewsList
                  items={this.cloneDeep(item)}
                  date={item.date}
                  onPress={() => {
                    history.push(this, '/newsDetails', {
                      details: this.cloneDeep(item),
                      type: item.type,
                    });
                  }}
                />
              )}
              keyExtractor={item => item.id}
            />
          </ViewShot>
        </ScrollView>
      </View>
    );
  }
}

function RenderNews(items) {
  console.log(items.items);
  return (
    <TouchableOpacity
      style={{marginTop: 10, marginBottom: 10, alignItems: 'center'}}>
      <View style={{width: width - 20, alignItems: 'center'}}>
        <Image
          style={{width: width - 40, height: 200}}
          source={{
            uri: items.items.image,
          }}
          // resizeMode={FastImage.resizeMode.contain}
        />
      </View>
      <View style={{width: width - 40, marginTop: 10}}>
        <Text style={{fontFamily: Fonts.ubuntu, color: colors.textColor}}>
          {items.items.title}
        </Text>
      </View>
      <View
        style={{
          height: 1,
          width: width - 40,
          backgroundColor: colors.textColor,
          marginTop: 15,
        }}
      />
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    borderWidth: 1,
    borderColor: '#000000',
    margin: 5,
    padding: 5,
    width: '70%',
    backgroundColor: '#DDDDDD',
    borderRadius: 5,
  },
  textField: {
    borderWidth: 1,
    borderColor: '#AAAAAA',
    margin: 5,
    padding: 5,
    width: '70%',
  },
  spacer: {
    height: 10,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 20,
    textAlign: 'center',
  },
});
