
import * as React from 'react';
import { NavigationContainer, Theme } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { RootStackParamList } from './types';
import { HomeScreen } from './screens/HomeScreen';
import LobyScreen from './screens/LobyScreen';
import { initContext } from './context/context';
import { GameScreen } from './screens/GameScreen';
import { RTMTWS } from './rtmt/rtmt_websocket';
import { ConnectionState } from './rtmt/rtmt';
import { useTranslation } from 'react-i18next';
import Snackbar from 'react-native-snackbar';

const Stack = createNativeStackNavigator<RootStackParamList>();

const context = initContext();

function App() {
  
  const { t } = useTranslation();

  const [userKey, setUserKey] = React.useState<string | undefined>(undefined);

  const [connectionState, setConnetionState] = React.useState<ConnectionState>("connecting");

  //@ts-ignore
  const [theme, setTheme] = React.useState<Theme>(context.themeManager.theme);

  const onConnectionError = (event: Event) => console.error("(RTMT) Connection Error: ", event);

  const onConnectionChange = (_connectionState: ConnectionState) => setConnetionState(_connectionState);

  const onThemeChange = (theme: Theme) => setTheme(theme);

  const connectRTMT = (userKey: string) => {
      const rtmt = context.rtmt as RTMTWS;
      rtmt.on("error", onConnectionError);
      rtmt.on("connectionchange", onConnectionChange)
      rtmt.connectWebSocket(userKey)
      return rtmt;
  }

  const loadUserKeyAndConnectServer = () => {
      context.userKeyStore.getUserKey().then((userKey: string) => {
          setUserKey(userKey);
          connectRTMT(userKey);
      }).catch((error) => {
          //TODO: check if it is network error!
          Snackbar.show({text: t("ErrorWhenRetrievingInformation")})
          console.error(error);
      });
  }

  const disposeApp = () => {
      context.rtmt?.dispose();
      context.themeManager.off("themechange", onThemeChange);
  }

  React.useEffect(() => {
      loadUserKeyAndConnectServer();
      context.themeManager.on("themechange", onThemeChange);
      return () => disposeApp();
  }, []);

  //const textColorOnBoard = getColorByBrightness(
  //    context.themeManager.theme.boardColor,
  //    context.themeManager.theme.textColor,
  //    context.themeManager.theme.textLightColor
  //);
  
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} initialParams={{context}} />
        <Stack.Screen name="Loby" component={LobyScreen} />
        <Stack.Screen name="Game" component={GameScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;