import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import { all, call, takeLatest, takeEvery, delay } from 'redux-saga/effects'

import { Connect, showErrorNotifaction } from '../util';
import { reducers } from './reducer';
import * as user from './user';
import * as datasource from './datasource';
import * as map from './map';
import * as datamodel from './datamodel';
import * as assetmanage from './assetmanage';
import * as tag from './tag';

const funcs = Connect({ user, datamodel, map, assetmanage, datasource, tag })

function* request(args) {
  const { type, payload, callback, error } = args.args;

  try {
    yield delay(100);
    const rs = yield call(funcs[type], payload)
    if (callback)
      yield call(callback, rs)
  } catch (ex) {
    if (ex) {
      ex.ApiError && ex.ApiError.cnMessage && showErrorNotifaction('系统异常', ex.ApiError.cnMessage, 5);
      error && error(ex);
    }
  }
}

function* watchLatest() {
  yield takeLatest('TAKE_LATEST', request)
}

function* watchLatestHomepage() {
  yield takeLatest('TAKE_LATEST_HOMEPAGE', request);
}

function* watchEvery() {
  yield takeEvery('TAKE_EVERY', request)
}

const sagaMiddleware = createSagaMiddleware()
export const store = createStore(
  reducers,
  applyMiddleware(sagaMiddleware)
)

function* rootSaga() {
  yield all([
    watchLatest(), watchLatestHomepage(), watchEvery()
  ])
}

sagaMiddleware.run(rootSaga)

export const dispatchLatest = ({ type, payload=null, callback=null, error=null }) => store.dispatch({ type: 'TAKE_LATEST', args: { type, payload, callback, error } })
export const dispatchLatestHomepage = ({ type, payload=null, callback=null, error=null }) => store.dispatch({ type: 'TAKE_LATEST_HOMEPAGE', args: { type, payload, callback, error } })
export const dispatch = ({ type, payload=null, callback=null, error=null }) => store.dispatch({ type: 'TAKE_EVERY', args: { type, payload, callback, error } })

export const action = ({ type, args}) => store.dispatch({ type, args })
