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,
    promptText: '',
  },
  reducers: {
    setPercent(state, { payload }) {
      return {
        ...state,
        percent: payload.progress,
      };
    },
    setPromptText(state, { payload }) {
      return {
        ...state,
        promptText: payload.promptText,
      };
    },
  },
  effects: {
    *init(ignored, { put, call }) {
      try {
        // yield call(codePush.sync);
        const result = yield call(checkUpdate);
        console.info(result);
        const { action, deploymentInfo, tokenId } = result;
        if (action === 'update' || action === 'rollback') {
          yield put({ type: 'setPromptText', payload: { promptText: `${action === 'update' ? '更新中...' : '回滚中'}` } });
          const token = encrypt(tokenId);
          yield call(
            update, `${config.updateContextPath}/resource/${token}/${encodeURIComponent(deploymentInfo.uri)}`,
            (event) => {
              app.getStore().dispatch({ type: 'welcome/setPercent', payload: { progress: event.progress } });
            },
          );
        }
      } 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',
        }));
      }
    },
  },
};
