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';
import app from '../index';

export default {
  namespace: 'welcome',
  state: {
    percent: 0,
  },
  reducers: {
    setPercent(state, { payload }) {
      return {
        ...state,
        percent: payload.progress,
      };
    },
  },
  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) => {
        //       app.getStore().dispatch({ type: 'welcome/setPercent', payload: { progress: event.progress } });
        //     },
        //   );
        //   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',
        }));
      }
    },
  },
};
