import React, {Component} from 'react';
import {StyleSheet, View, Text, Image, ActivityIndicator} from 'react-native';
import JMessage from 'jmessage-react-plugin';
import JPush from 'jpush-react-native';
import history from '../../common/history';
import AsyncStorageHelper from '../../common/asyncStorageHelper';
import moment from 'moment';
import {queryUser} from '../../services/realm/realmManger';
import Global from '../../services/Global';
//import { NimSession } from 'react-native-netease-im'
import {inject, observer} from 'mobx-react';
import {observable} from 'mobx';
import {scale, verticalScale, moderateScale} from 'react-native-size-matters';
import language from '../../services/language';
import {isTSUndefinedKeyword} from '@babel/types';
import {colors} from '../../assets/styles/colors-theme';
import {Fonts} from '../../assets/styles/fonts-theme';
import Size from '../../common/size';
const size = new Size();
const asyncStorageHelper = new AsyncStorageHelper();
@inject('appStore')
@observer
export default class SplashScreen extends Component {
  @observable
  notificationId = '';
  constructor(props) {
    super(props);
    this.store = props.appStore;
  }

  async componentWillMount() {}

  async componentDidMount() {
    // Preload data from an external API
    // Preload data using AsyncStorage

    this.init();
    // this.props.navigation.navigate('mainPage');
    // }
  }

  async init() {
    // this.store.getRegistrationID()
    this.connectListener = result => {
      console.log('connectListener:' + JSON.stringify(result));
    };
    this.store.splash = true;
    let user = await queryUser();
    // console.log(user.id)
    let count = user.length;

    asyncStorageHelper.getData('language', data => {
      console.log(data);
      console.log('hi');
      if (data != null) {
        switch (data) {
          case '"english"':
            console.log('english');
            this.store.text = language.en;
            this.store.languageSelection = 'english';
            break;

          case '"hk"':
            console.log('hk');
            this.store.text = language.hk;
            this.store.languageSelection = 'hk';
            break;
          case '"ch"':
            console.log('chinese');
            this.store.text = language.ch;
            this.store.languageSelection = 'ch';
            break;
        }
      } else {
        try {
          console.log('hk');
          this.store.text = language.hk;
          this.store.languageSelection = 'hk';
          console.log(this.store.languageSelection);
        } catch (error) {
          console.log(error);
        }
      }
    });
    console.log(count);
    if (count > 0) {
      await this.getUser();
      await this.login();
      //this.props.navigation.navigate("mainPage");
    } else {
      console.log('testing');
      this.store.selectChar = true;
      this.props.navigation.navigate('SelectChar');
    }
  }

  async loginAction(userInfo) {
    //await this.store.loginPost(userInfo, this, true);
    await this.store.getUserProfile(userInfo, this);
    // console.log(userInfo.pwd)
    //  await this.props.linkAction.login('testphiliptesttest', 'cefef77be727e823969bfb9c6a01fa63', (error) => {
    //    if (error) {
    //     //  if (this.toast) {
    //     //    this.toast.show(util.parseDisconnectMsg(error));
    //     //  }
    //     console.log(error)
    //      //this.props.navigation.navigate('login');
    //      console.log(util.parseDisconnectMsg(error))
    //    } else {
    //      console.log('ok')
    //      // if (this.props.navigation.state.routeName === 'login') {
    //      //   this.props.navigation.navigate('session');
    //      // }
    //      // AsyncStorage.setItem('isLogin', 'true');
    //    }
    //  });
  }

  async login() {
    await asyncStorageHelper.getData('userInfo', async userInfo => {
      if (userInfo != null) {
        console.log(userInfo);
       await this.loginAction(userInfo);
      } else {
        //  this.store.regUserNotificationToken(false,false);
        if (this.store.user.memberType == 0) {
          this.props.navigation.navigate('main');
        } else {
          this.props.navigation.navigate('signin', {icon: false});
        }
      }
    });
  }

  getUser = async () => {
    let user = queryUser();
    for (let p of user) {
      this.store.user = p;
      console.log(this.store.user);
      this.store.user.apartment.map((items, index) => {
        console.log(items);
      });
    }
  };

  render() {
    return (
      <View style={styles.viewStyles}>
        <Image source={require('../../assets/images/logo.png')} />
        <ActivityIndicator size="small" color="white" style={{marginTop: 20}} />
      </View>
    );
  }
}

const styles = StyleSheet.flatten({
  viewStyles: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: colors.mainColor,
  },
  textStyles: {
    color: 'white',
    fontSize: 40,
    fontWeight: 'bold',
  },
});
