import "./App.css";
import React, { useState, useEffect } from "react";
import { BrowserRouter } from "react-router-dom";

import HeaderBar from "./components/HeaderBar/HeaderBar";
import Layout from "./hoc/Layout/Layout";
import PageRouter from "./hoc/PageRouter/PageRouter";

import { AuthContext } from "./context/AuthContext";
import { auth, onAuthStateChange } from "./services/firebase";

export const NO_COMPETITION = 0;

function App() {
  const [user, setUser] = useState({ signedIn: false });
  const [authStateReceived, setAuthStateReceived] = useState(false);
  const [compId, setCompId] = useState(NO_COMPETITION);
  const [competitionInfo, setCompetitionInfo] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const unsubscribe = onAuthStateChange((userData) => {
      setUser(userData);
      setAuthStateReceived(true);
    });
    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    const parsedCompId = Number(
      localStorage.getItem("compId") || NO_COMPETITION
    );
    setCompId(parsedCompId);
  }, []);

  const fetchCompetitionInfo = async (fetchCall, stateKey) => {
    try {
      const data = await fetch(fetchCall).then((response) => response.json());
      return {
        [stateKey]: data,
      };
    } catch (e) {
      return {
        [stateKey]: undefined,
      };
    }
  };

  const isReadyForDataFetch = () => {
    if (!user.signedIn) return false;
    if (user.id === undefined || user.id === 0) return false;
    if (compId === NO_COMPETITION) return false;
    return true;
  };

  const fetchData = () => {
    setLoading(true);
    Promise.all([
      fetchCompetitionInfo(
        `./competitionInfo?user=${user.id}&competition=${compId}`,
        "generalInfo"
      ),
      fetchCompetitionInfo(`./recentBuys?competition=${compId}`, "recentBuys"),
      fetchCompetitionInfo(
        `./investments?user=${user.id}&competition=${compId}`,
        "investments"
      ),
      fetchCompetitionInfo("./trending", "trending"),
      fetchCompetitionInfo(`./networths?competition=${compId}`, "networths"),
      fetchCompetitionInfo(
        `./rankedCompetitors?competition=${compId}`,
        "rankings"
      ),
    ]).then((resolvedData) => {
      setLoading(false);
      let newCompInfo = {};
      for (const response of resolvedData) {
        newCompInfo = {
          ...newCompInfo,
          ...response,
        };
      }
      setCompetitionInfo(newCompInfo);
    });
  };

  useEffect(() => {
    if (!authStateReceived) {
      return;
    }
    if (isReadyForDataFetch()) {
      fetchData();
    }
  }, [user.id, authStateReceived]);

  return (
    <BrowserRouter>
      <div className="App">
        <AuthContext>
          <HeaderBar
            loggedIn={user.signedIn}
            innerNav={compId != NO_COMPETITION}
            updateCompId={setCompId}
          />
          <Layout>
            <PageRouter
              authStateReceived={authStateReceived}
              signedIn={user.signedIn}
              compId={compId}
              loading={loading}
              competitionInfo={competitionInfo}
              updateCompId={setCompId}
              updateInfo={fetchData}
            />
          </Layout>
        </AuthContext>
      </div>
    </BrowserRouter>
  );
}

export default App;

@@ -2501,16 +2501,745 @@
 ;%0A  %7D;%0A%0A
+  const fetchPartialData = () =%3E %7B%0A    setLoading(true);%0A    Promise.all(%5B%0A      fetchCompetitionInfo(%0A        %60./competitionInfo?user=$%7Buser.id%7D&competition=$%7BcompId%7D%60,%0A        %22generalInfo%22%0A      ),%0A      fetchCompetitionInfo(%0A        %60./investments?user=$%7Buser.id%7D&competition=$%7BcompId%7D%60,%0A        %22investments%22%0A      ),%0A    %5D).then((resolvedData) =%3E %7B%0A      setLoading(false);%0A      let newPartialInfo = %7B%7D;%0A      for (const response of resolvedData) %7B%0A        newPartialInfo = %7B%0A          ...newPartialInfo,%0A          ...response,%0A        %7D;%0A      %7D%0A      let newCompInfo = %7B%0A        ...competitionInfo,%0A        ...newPartialInfo,%0A      %7D;%0A      console.log(newCompInfo);%0A      setCompetitionInfo(newCompInfo);%0A    %7D);%0A  %7D;%0A%0A
   useEff
@@ -3942,24 +3942,31 @@
 eInfo=%7Bfetch
+Partial
 Data%7D%0A      

Refactor update data flow to make it slightly less inefficient