import { AsyncStorage } from 'react-native';
import { NavigationActions } from 'react-navigation';
// import codePush from 'react-native-code-push';
import { checkUpdate } from '../services/update';
import { update } 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(update);
          // console.info(`${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`);
          yield call(update, `${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`, () => { console.info('xxx'); });
        }
      } 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',
        }));
      }
    },
  },
};
