import {useAppSelector, useAppDispatch} from 'hooks/store';
import AuthenticationService from './services/authentication.service';
import {useEffect, useState} from 'react';
import {authenticationActions, selectError, selectIsAuthenticated, selectCredentials} from 'store/slices/Authentication.slice';
import hostService from 'services/url.service';
import LoggerFactory from './services/logger/LoggerFactory';
import Router from 'routers/router';
import PCastApiService from './services/pcast-api.service';
import { ApplicationCredentials } from '@techniker-me/pcast-api';

export default function App() {
  const dispatch = useAppDispatch();
  const [isInitialized, setIsInitialized] = useState(false);
  const error = useAppSelector(selectError);
  const credentials = useAppSelector(selectCredentials);
  const isAuthenticated = useAppSelector(selectIsAuthenticated);

  useEffect(() => {
    LoggerFactory.applyLoggerConfig();

    if (!isInitialized) {
      AuthenticationService.setWebSocketUri(hostService.getWebSocketUrl());
      setIsInitialized(true);
      AuthenticationService.status?.subscribe(status => dispatch(authenticationActions.setStatus(status)));
    }
  }, [dispatch, isInitialized]);

  useEffect(() => {
    if (credentials.applicationId && credentials.secret && isAuthenticated) {
      const appCredentials: ApplicationCredentials = {
        id: credentials.applicationId,
        secret: credentials.secret
      };
      PCastApiService.initialize(hostService.getPcastBaseUrlOrigin(), appCredentials);
    }
  }, [credentials, isAuthenticated]);

  return (
    <>
      {error && <div>{error}</div>}
      <Router />
    </>
  );
}
