/**
 * @flow
 */
import _ from 'lodash';
import { applyMiddleware } from 'redux';

//import stringify from 'json-stringify-safe'
import toast from '../components/Toast';
//import { startLoading, finishLoading } from '../actions/loading'


function thunkState({ dispatch, getState }) {
  return next => (action) => {
    try {
      if (getState().loading.loadingQueue.length <= 0) {
        //dispatch(finishLoading())
      }
    } catch (e) {
      //dispatch(finishLoading())
    }
    if (action && typeof action === 'function') {
      return dispatch(action(getState()));
    }
    return next(action);
  };
}

function promise({ dispatch }) {
  return next => (action) => {
    if (action && typeof action.then === 'function') {
      //dispatch(startLoading())
      const finishLoadingAndDispatch = (input) => {
        //dispatch(finishLoading())
        dispatch(input);
      };
      return action.then(finishLoadingAndDispatch).catch(finishLoadingAndDispatch);
    }
    return next(action);
  };
}

function multiDispatcher({ dispatch }) {
  return next => (actions) => {
    if (Array.isArray(actions)) {
      return actions.map(action => dispatch(action));
    }
    return next(actions);
  };
}

//export function writeLog(msg:string) {
//  try {
//    //LogReporter.write('\r\n')
//    //LogReporter.write(`time:${new Date().toLocaleDateString()}`)
//    const newMsg = typeof msg === 'string' ? msg : JSON.stringify(msg)
//    //LogReporter.write(`message:${newMsg}`)
//  } catch (e) {
//    // noting to do
//  }
//}
function errorHandler({ dispatch }) {
  return next => (action) => {
    if (action instanceof Error) {
      const chinesePatten = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;
      const msg = action.message || '';

      const isFaceBookError = (msg || '').toLowerCase().includes('facebook.github.io');
      if (!isFaceBookError) {
        const position = ['\npos:{ line:', action.line, ',col:', action.column, ' }'];
        const devMsg = [msg, ...position].join('');

        if (__DEV__) {
          toast(devMsg);
        } else if (chinesePatten.test(msg)) {
          toast(msg);
        }
        //logger({ error: true, message: devMsg, action })
      }
      // writeLog(msg)
      return action;
    }

    try {
      return next(action);
    } catch (error) {
      return dispatch(error);
    }
  };
}
//
//function logTracker({ getState }) {
//  const actionBuffer = []
//  const key = 'RC@Qv!gw6hW8Yc0z'
//  global.ErrorUtils.setGlobalHandler((e, isFatal) => {
//    actionBuffer.push({ e, isFatal })
//    const log = stringify({
//      actionBuffer,
//      state: getState(),
//    })
//    const logEncrypted = CryptoJS.AES.encrypt(log, key).toString()
//    // LogReporter.write(logEncrypted)
//  })
//  return next => action => {
//    const actionItem = {}
//    actionItem.action = action
//    actionItem.time = new Date()
//    actionBuffer.push(actionItem)
//    if (actionBuffer.length > 20) {
//      actionBuffer.shift()
//    }
//    return next(action)
//  }
//}

const filterNil = () => next => (action) => {
  if (action != null) {
    next(action);
  }
};

const businessHandle = ({ dispatch }) => next => (action) => {
  if (action && !_.isEmpty(action.action)) {
    // writeLog(`actionId:${action.action} actionName: ${action.name}`)
    return dispatch(action.method(action.params));
  }
  return next(action);
};

export default applyMiddleware(
  multiDispatcher,
  errorHandler,
  promise,
  thunkState,
  filterNil,
  businessHandle,
);
