local A=game:GetService("\082\101\112\108\105\099\097\116\101\100\083\116\111\114\097\103\101")local v=A:WaitForChild("\108\105\098")local Y=A:WaitForChild("\099\111\109\109\111\110")local i=require(Y:WaitForChild("\083\101\108\101\099\116\111\114\115"))local C if game.PlaceId~=0 then C=require(v:WaitForChild("\068\097\116\097\083\116\111\114\101\050"))end return function(A,v)return function(Y)local R=v:getState()A(Y)if Y.player and Y.type~="\080\076\065\089\069\082\095\082\069\077\079\086\069"then local A=Y.player local M=v:getState()local k=i.getPlayerState(R,A)local H=i.getPlayerState(M,A)if game.PlaceId~=0 then if H and k then local v=C("\115\097\118\101\068\097\116\097",A)v:Set(H)end end end end end
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local lib = ReplicatedStorage:WaitForChild("lib")
local common = ReplicatedStorage:WaitForChild("common")

local Selectors = require(common:WaitForChild("Selectors"))

local DataStore2
if game.PlaceId ~= 0 then
    DataStore2 = require(lib:WaitForChild("DataStore2"))
end

return function(nextDispatch,store)
    return function(action)
        local prevState = store:getState()
        nextDispatch(action)
        if action.player and action.type ~= "PLAYER_REMOVE" then -- this action is modifying a players state
            local player = action.player
            local nextState = store:getState()
            local prevSaveTable = Selectors.getPlayerState(prevState,player)
            local playerSaveTable = Selectors.getPlayerState(nextState,player)
            if game.PlaceId ~= 0 then
                -- if prev save table is nil then the player has just joined, no need to save.
                if playerSaveTable and prevSaveTable then
                    local saveStore = DataStore2("saveData",player)
                    saveStore:Set(playerSaveTable)
                end
            end
        end
    end
end