import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk';
import promiseReducer from './reducers/promise-reducer'
import { combineReducers  } from "redux";
import authReducer from './reducers/auth-reducer'
import {history} from '../history'
import chatsReducer from './reducers/chat-reducer';
import {actionAuthLogout} from './actions/action-logout'
import {actionCreateMessage} from './actions/action-create-msg'
import {actionMsgOne} from './actions/actionMsgOn'
import { actionAboutMe } from './actions/action-aboutMe';
import { OpenChatPage } from '../pages/OpenChatPage';


const store = createStore(
    combineReducers({
        auth: authReducer,
        promise: promiseReducer,
        chat: chatsReducer
    }),
    applyMiddleware(thunk)

    
);

export const socket = window.io("ws://chat.ed.asmer.org.ua");

socket.on("jwt_ok", (data) => console.log(data));
socket.on("jwt_fail", (error) => {
    console.log(error);
});

socket.on("msg", (msg) => {
    console.log("пришло смс");
    console.log(msg)

    store.dispatch(actionMsgOne(msg))
    
});

socket.on("chat", (chat) => {
    console.log("нас добавили в чат");
    const state = store.getState();
    socket.emit("jwt", state.auth.token);
});

socket.on("chat_left", (chat) => {
    console.log("нас выкинули из чата");
});


store.subscribe(() => {
    const authToken = store.getState().auth?.token;
    if (!authToken) {
        history.push('/')
    }

console.log(store.getState())})

export default store