import {onSnapshot, applySnapshot, onPatch, applyPatch, onAction, applyAction} from 'mobx-state-tree';

let subscription;
export default function syncStoreWithBackend(socket, store) {





    subscription = onAction(store, (data, next) => {
        next()
        socketSend(data)
    })

    onSocketMessage((data) => {
        applyAction(store, data)
    })









    let isHandlingMessage = false
    function socketSend(data) {
        if (!isHandlingMessage)
            socket.send(JSON.stringify(data))
    }

    function onSocketMessage(handler) {
        socket.onmessage = event => {
            isHandlingMessage = true
            handler(JSON.parse(event.data))
            isHandlingMessage = false
        }
    }
}








/**
 * Clean up old subscription when switching communication system
 */
if (module.hot) {
    module.hot.dispose((data) => {
        subscription()
    });
}
@@ -178,20 +178,16 @@
 ore) %7B%0A%0A
-%0A%0A%0A%0A
     subs
@@ -235,23 +235,8 @@
 %3E %7B%0A
-        next()%0A
     
@@ -252,24 +252,46 @@
 tSend(data)%0A
+        return next()%0A
     %7D)%0A%0A    
@@ -351,24 +351,24 @@
 , data)%0A
+
     %7D)%0A%0A
 %0A%0A%0A%0A%0A%0A%0A%0A
@@ -359,24 +359,16 @@
     %7D)%0A%0A
-%0A%0A%0A%0A%0A%0A%0A%0A
     let 
@@ -726,23 +726,16 @@
    %7D%0A%7D%0A%0A
-%0A%0A%0A%0A%0A%0A%0A
 /**%0A * C

clean up socket