import {Component, createElement} from 'react'
import Rx from 'rxjs'

let _debug = false;
let debug = (flag) => _debug = flag;

let actionFlow = new Rx.Subject();
let changeFlow = new Rx.BehaviorSubject({});
let stateFlow = new Rx.BehaviorSubject({});

actionFlow.scan((currentState, update) => {
    let change = update instanceof Function ? update(currentState) : update;
    let newState = Object.assign(currentState, change);
    if (_debug) {
        console.log(`change: ${JSON.stringify(change)}`);
        console.log(`newState: ${JSON.stringify(newState)}`);
    }
    changeFlow.next(change);
    return newState;
}, {})
    .subscribe(state => stateFlow.next(state));


let connect = (WrappedComponent) => {
    class Connect extends Component {
        componentWillMount() {
            this.setState(stateFlow.getValue());
            this.subscription = changeFlow.subscribe(state => this.setState(state));
        }

        componentWillUnmount() {
            this.subscription.unsubscribe();
        }

        render() {
            return createElement(WrappedComponent, Object.assign({}, this.state, this.props));
        }
    }
    return Connect;
}

let next = (state) => actionFlow.next(state);
let initState = next;

export {connect, next, initState, debug};
@@ -83,18 +83,20 @@
  false;%0A
-le
+cons
 t debug 
@@ -123,18 +123,20 @@
  flag;%0A%0A
-le
+cons
 t action
@@ -160,18 +160,20 @@
 ject();%0A
-le
+cons
 t change
@@ -207,18 +207,20 @@
 ct(%7B%7D);%0A
-le
+cons
 t stateF
@@ -682,18 +682,20 @@
 te));%0A%0A%0A
-le
+cons
 t connec
@@ -1178,18 +1178,20 @@
 ect;%0A%7D%0A%0A
-le
+cons
 t next =
@@ -1226,18 +1226,20 @@
 state);%0A
-le
+cons
 t initSt

use const