import * as api from '../services/hkvs';

export default {
  namespace: 'hkvs',
  state: {
    capture: {},
  },
  reducers: {
    setDevices(state, {data}) {
      state.device = data.device || true;
      state.deviceIn = data.deviceIn;
      state.deviceOut = data.deviceOut;
      return {...state};
    },
    setCapture(state, {device, data}) {
      const {capture} = state;
      if (device === state.deviceIn) {
        // if (!capture.in) capture.in = [];
        capture.in = data;
      } else if (device === state.deviceOut) {
        // if (!capture.out) capture.out = [];
        capture.out = data;
      }
      return {...state};
    },
  },
  effects: {
    *devices(action, {put, call}) {
      const {data} = yield call(api.devices);
      yield put({type: 'setDevices', data: data.data});
    },
    *capture({device}, {put, call}) {
      let res = yield call(api.capture, device);
      if (res.data.code !== 1) {
        // 重试一遍
        res = yield call(api.capture, device);
      }
      if (res.data.code !== 1) {
        // 重试一遍
        res = yield call(api.capture, device);
      }
      if (res.data.code === 1) {
        yield put({type: 'setCapture', device, data: res.data.data});
        return res.data.data;
      }
      return null;
    },
  },
};
