import { AsyncStorage } from 'react-native';
import { NavigationActions } from 'react-navigation';
// import codePush from 'react-native-code-push';
import { checkUpdate } from '../services/update';
import { addUpdaterDownloadingCallback, update, addUpdaterDownloadedCallback } from '../native/Updater';
import config from '../utils/config';
import { encrypt } from '../utils/helper';

export default {
  namespace: 'welcome',
  state: { },
  reducers: {},
  effects: {
    *init(ignored, { put, call }) {
      try {
        // yield call(codePush.sync);
        const result = yield call(checkUpdate);
        const { action, deploymentInfo, tokenId } = result;
        if (action === 'update') {
          const token = encrypt(tokenId);
          // console.info(`${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`);
          console.log('开始');
          yield call(update, `${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`, (event) => { console.info(event); });
          console.log('结束结束结束结束结束结束结束结束结束结束');
        }
      } catch (e) {
        console.log(e); // eslint-disable-line no-console
      }
      const token = yield call(AsyncStorage.getItem, 'token');
      if (!token) {
        yield put(NavigationActions.navigate({
          routeName: 'Login',
        }));
      } else {
        yield put(NavigationActions.navigate({
          routeName: 'Main',
        }));
      }
    },
  },
};
