import { createStore } from 'redux'
import { cloneDeep, result, isEqual } from 'lodash'
import reducer from './reducer'

const _store = createStore(reducer)

const store = cloneDeep(_store)

/**
 * 允许传入第一个参数path,只监听指定属性路径的对象
 * @param  {...any} args 
 * @returns 
 */
store.subscribe = (...args) => {
    let path,
        listener,
        snapshot

    if (typeof args[0] === 'string' && typeof args[1] === 'function') {
        path = args[0]
        listener = args[1]
        snapshot = cloneDeep(result(_store.getState(), path))
    } else {
        listener = args[0]
    }

    return _store.subscribe((...args) => {
        const state = _store.getState()
        if (path) {
            const resultState = cloneDeep(result(state, path))
            if (!isEqual(snapshot, resultState)) {
                listener.apply(this, [resultState, ...args])
            }
            snapshot = resultState
        } else {
            listener.apply(this, [state, ...args])
        }
    })
}

/**
 * 允许传入参数path,只返回指定属性路径的对象
 * @param {*} path 
 * @returns 
 */
store.getState = (path) => {
    if (path) {
        return result(_store.getState(), path)
    }

    return _store.getState()
}

export default store