import { applyMiddleware, combineReducers, createStore } from 'redux';
import thunk from 'redux-thunk';
import { Provider,connect } from 'react-redux';
import './App.scss';
import { backendURL, gql } from './helpers/gql';
import { useEffect, useState, useRef } from 'react';
import { authReducer } from './reducers/authReducer';
import {promiseReducer } from './reducers/promiseReducer';
import React, { Component } from 'react';
import {Router, Route, Link,  Navigate, Switch, Redirect} from 'react-router-dom';
import { createBrowserHistory } from 'history'


import LoginPage from './pages/LoginPage';
import RegisterPage from './pages/RegisterPage';
import {MainPage} from './pages/MainPage';
import { actionAuthLogout } from './actions/actionLogin';

import { actionPromise } from './actions/actionsPromise';
import { socket } from './actions/actionLogin';
import { actionAboutMe } from './actions/actionAboutMe';



import {chatReducer} from './reducers/chatReducer';
import ModalNewChat from './components/CreateNewChat';
import { modalReducer } from './reducers/modalReducer';
import { actionGetMessageFromSocket } from './actions/actionsMessages';
import { actionGetOneChat, actionLeftChat } from './actions/actionsForChats';


// import { uploadFile } from '../helpers/uploadFile';

export const history = createBrowserHistory();












export const store = createStore(combineReducers({
		promise: promiseReducer, auth: authReducer, chats: chatReducer, modal: modalReducer
	}), applyMiddleware(thunk))
console.log(store.getState())
store.subscribe(() => console.log(store.getState()));


if (localStorage.authToken) socket.emit('jwt', localStorage.authToken)

socket.on('jwt_ok',   data => console.log(data))
socket.on('jwt_fail', error => console.log(error))
socket.on('msg', msg => {console.log('from socket msg', msg); store.dispatch(actionGetMessageFromSocket(msg))})
socket.on('chat', chat => {console.log('from socket chat', chat); if (localStorage.authToken) {socket.emit('jwt', localStorage.authToken)}; store.dispatch(actionGetOneChat(chat._id))})
socket.on('chat_left', chat => {console.log('from socket chat_left', chat); store.dispatch(actionLeftChat(chat)) });
socket.on('media', media => console.log(media));

socket.on("connect", () => {
	console.log(socket.id)
})



const AllRoutes = ({auth}) => {
	return (
				<Switch>
					<Route path="/login" component={LoginPage}/>
					<Route path="/register" component={RegisterPage}/>
					<Route path="/main" component={MainPage} />
					<Route exact path="/">{auth ? <Redirect to="/main"/> : <Redirect to="/login" /> }</Route>
				</Switch>
			)
}

const CAllRoutes = connect(state => ({auth : state.auth?.payload}))(AllRoutes)




function App() {
	
  return (
	<Router history={history}>
		<Provider store={store}>
			<div className="App">
				<CAllRoutes />
			</div>
			
		</Provider>
 	</Router>
  );
}

export default App;

