import { Model, routerRedux } from "dva";
import _ from 'lodash';
import { PageState, CoinUnion } from '@/types/common';
import { getCoins, calcRate } from './service';

export interface MineModelState {
  coins: CoinUnion[];
  pageState: PageState;
  coin: CoinUnion | null;
  srcValue: string;
  dstValue: string;
}

const initState: MineModelState = {
  coins: [],
  coin: null,
  pageState: PageState.Pending,
  srcValue: '1',
  dstValue: '1',
};

const model: Model = {
  namespace: 'mine',

  state: initState,

  effects: {
    *load(_, { put, call }) {
      yield put({ type: 'onUpdateState', pageState: PageState.Pending });
      try {
        const coins: CoinUnion[] = yield call(getCoins);
        const coin = coins[0];
        yield put({
          type: 'onUpdateState',
          pageState: PageState.Success,
          coins,
          coin,
          srcValue: '1',
          dstValue: calcRate('1', coin && coin.rate),
        });
      } catch (e) {
        yield put({
          type: 'onUpdateState',
          pageState: PageState.Failure,
        });
      }
    },

    *selectCoin({ payload: id }, { put, select }) {
      const { coins, srcValue } = yield select((state: any) => state.mine);
      const coin = _.find(coins, ['id', id]);
      yield put({
        type: 'onUpdateState',
        coin,
        dstValue: calcRate(srcValue, coin && coin.rate),
      });
    },

    *changeSrc({ payload }, { put, select }) {
      if (isNaN(payload)) return;
      const { coin } = yield select((state: any) => state.mine);
      yield put({
        type: 'onUpdateState',
        srcValue: payload,
        dstValue: calcRate(payload, coin && coin.rate),
      });
    },
  },

  reducers: {
    onUpdateState(state, payload) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default model;
