
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 { Context, initContext } from './context/context';
import { GameScreen } from './screens/GameScreen';
import { RTMTWS, ConnectionState } from '@mancala/core';
import { useTranslation } from 'react-i18next';
import Snackbar from 'react-native-snackbar';
import { NativeModules, I18nManager, Platform } from 'react-native'

// https://github.com/uuidjs/uuid/issues/514#issuecomment-691475020
import 'react-native-get-random-values';
import HelpScreen from './screens/HelpScreen';
import { getColorByBrightness } from "@mancala/core";
import { server } from './const/config';

const Stack = createNativeStackNavigator<RootStackParamList>();

const context = initContext();

function App() {

  // Get device language
  const deviceLanguage =
    Platform.OS === 'ios'
      ? NativeModules.SettingsManager.settings.AppleLocale // iOS
      : NativeModules.I18nManager.localeIdentifier; // Android


  const { t, i18n } = useTranslation();

  React.useEffect(() => {
    i18n.changeLanguage(deviceLanguage === "tr_TR" ? "tr" : "en")
  }, []);

  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) => {
    //Snackbar.show({text: getTextByConnectionState(context, _connectionState)})
    return 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)
    const url = server.wsServerAdress + "?userKey=" + userKey;
    rtmt.connectWebSocket(url, userKey)
    return rtmt;
  }
  const getTextByConnectionState = (context: Context, connectionState: ConnectionState): string => {
    const map: { [key: string]: string } = {
        connecting: t('Connecting'),
        connected: t('Connected'),
        error: t('CannotConnect'),
        closed: t('ConnectingAgain'),
        reconnecting: t('ConnectingAgain'),
    };
    return map[connectionState];
}

  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
  //);
  const textColorOnAppBar = getColorByBrightness(
    context.themeManager.theme.appBarBgColor,
    context.themeManager.theme.textColor,
    context.themeManager.theme.textLightColor
  );

  const headerStyle = { backgroundColor: context.themeManager.theme.appBarBgColor };
  const headerTintColor = textColorOnAppBar;

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} initialParams={{ context }}
          options={{ title: t("Mancala"), headerStyle, headerTintColor }} />
        <Stack.Screen name="Loby" component={LobyScreen}
          options={{ title: t("Mancala"), headerStyle, headerTintColor }} />
        <Stack.Screen name="Game" component={GameScreen}
          options={{ title: t("Mancala"), headerStyle, headerTintColor }} />
        <Stack.Screen name="Help" component={HelpScreen}
          options={{ title: t("Help"), headerStyle, headerTintColor }} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;