Skip to content

Commit

Permalink
#PrivateLobbies
Browse files Browse the repository at this point in the history
- homestretch
  • Loading branch information
CheBato committed Jan 3, 2025
1 parent 30c64f0 commit e718d05
Show file tree
Hide file tree
Showing 9 changed files with 161 additions and 150 deletions.
12 changes: 7 additions & 5 deletions src/app/_components/HomePage/HomePagePlayMode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,17 @@ const HomePagePlayMode: React.FC = () => {
<Card variant="black">
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<Tabs value={value} variant="fullWidth" onChange={handleChange}>
<Tab sx={styles.tabStyles} label="Play" />
{user && <Tab sx={styles.tabStyles} label="Play" />}
<Tab sx={styles.tabStyles} label="Create" />
{showTestGames && <Tab sx={styles.tabStyles} label="Test" />}
</Tabs>
</Box>
<TabPanel index={0} value={value}>
<QuickGameForm/>
</TabPanel>
<TabPanel index={1} value={value}>
{user &&
<TabPanel index={0} value={value}>
<QuickGameForm/>
</TabPanel>
}
<TabPanel index={user ? 1 : 0} value={value}>
<CreateGameForm format={'Premier'} />
</TabPanel>
{showTestGames &&
Expand Down
4 changes: 2 additions & 2 deletions src/app/_components/Lobby/Deck/Deck.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ const Deck: React.FC = () => {
const connectedUser = lobbyState ? lobbyState.users.find((u: ILobbyUserProps) => u.id === connectedPlayer) : null;

// set decks for connectedUser
const newDeck = connectedUser ? connectedUser.deck.deckCards || [] : [];
const sideBoard = connectedUser ? connectedUser.deck.sideboard || [] : [];
const newDeck = connectedUser ? connectedUser.deck ? connectedUser.deck.deckCards || [] : [] : [];
const sideBoard = connectedUser ? connectedUser.deck ? connectedUser.deck.sideboard || [] : [] : [];

// Calculate the total counts
const deckCount = newDeck.reduce(
Expand Down
8 changes: 4 additions & 4 deletions src/app/_components/Lobby/Players/Players.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ const Players: React.FC<IPlayersProps> = ({ isLobbyView }) => {
const opponentUser = lobbyState ? lobbyState.users.find((u: ILobbyUserProps) => u.id !== connectedPlayer) : null;

// set connectedPlayer
const playerLeader = connectedUser ? connectedUser.deck.leader[0].card : null;
const playerBase = connectedUser ? connectedUser.deck.base[0].card : null;
const playerLeader = connectedUser ? connectedUser.deck ? connectedUser.deck.leader[0].card : null : null;
const playerBase = connectedUser ? connectedUser.deck ? connectedUser.deck.base[0].card : null : null;

// set opponent
const titleOpponent = opponentUser ? opponentUser.username : null;
const opponentLeader = opponentUser ? opponentUser.deck.leader[0].card : null;
const opponentBase = opponentUser ? opponentUser.deck.base[0].card : null;
const opponentLeader = opponentUser ? opponentUser.deck ? opponentUser.deck.leader[0].card : null : null;
const opponentBase = opponentUser ? opponentUser.deck ? opponentUser.deck.base[0].card : null : null;
const cardStyle = {
borderRadius: '1.1em',
borderColor: '#FFFFFF00',
Expand Down
2 changes: 1 addition & 1 deletion src/app/_components/Lobby/SetUp/SetUp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const SetUp: React.FC = ({
const mainCardStyle = {
borderRadius: '1.1em',
height: '100%',
maxHeight: '72.5vh',
maxHeight: lobbyState && lobbyState.privacy === 'Public' ? '72.5vh': '64.4vh',
width: '100%',
display: 'flex',
flexDirection: 'column',
Expand Down
59 changes: 54 additions & 5 deletions src/app/_components/Lobby/_subcomponents/SetUpCard/SetUpCard.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import React from 'react';
import React, { ChangeEvent, useState } from 'react';
import {
Card,
CardContent,
Typography,
TextField,
Button,
Box, CardActions,
Box, CardActions, Link, FormControl,
} from '@mui/material';
import { useGame } from '@/app/_contexts/Game.context';
import { useRouter } from 'next/navigation'
import { ILobbyUserProps, ISetUpProps } from '@/app/_components/Lobby/LobbyTypes';
import StyledTextField from '@/app/_components/_sharedcomponents/_styledcomponents/StyledTextField/StyledTextField';
import { fetchDeckData } from '@/app/_utils/fetchDeckData';

const SetUpCard: React.FC<ISetUpProps> = ({
readyStatus,
owner,
}) => {
const { sendMessage, lobbyState, connectedPlayer, sendLobbyMessage } = useGame();
const { lobbyState, connectedPlayer, sendLobbyMessage } = useGame();
const [deckLink, setDeckLink] = useState<string>('');
const opponentUser = lobbyState ? lobbyState.users.find((u: ILobbyUserProps) => u.id !== connectedPlayer) : null;
const currentUser = lobbyState ? lobbyState.users.find((u: ILobbyUserProps) => u.id === connectedPlayer) : null;
// Extract the player from the URL query params
const router = useRouter();

Expand All @@ -25,6 +29,11 @@ const SetUpCard: React.FC<ISetUpProps> = ({
sendLobbyMessage(['onStartGame']);
router.push('/GameBoard');
};
const handleOnChangeDeck = async () => {
console.log('SWUDB Deck Link:', deckLink);
const deckData = deckLink ? await fetchDeckData(deckLink) : null;
sendLobbyMessage(['changeDeck',deckData])
}

// ------------------------STYLES------------------------//
const styles = {
Expand Down Expand Up @@ -67,7 +76,7 @@ const SetUpCard: React.FC<ISetUpProps> = ({
minWidth: '9rem',
},
initiativeCardStyle: {
height: '15vh',
height: lobbyState && lobbyState.privacy === 'Public' ? '15vh' : '23vh',
minHeight: '8.5rem',
background: '#18325199',
display: 'flex',
Expand All @@ -87,6 +96,21 @@ const SetUpCard: React.FC<ISetUpProps> = ({
color: 'white',
alignSelf: 'flex-start',
},
labelTextStyle: {
mb: '.5em',
mt: '1.5em',
color: 'white',
},
labelTextStyleSecondary: {
color: '#aaaaaa',
display: 'inline',
},
submitButtonStyle: {
display: 'block',
ml: 'auto',
mr: 'auto',
mt: '10px',
},
}
return (
<Card sx={styles.initiativeCardStyle}>
Expand All @@ -102,7 +126,7 @@ const SetUpCard: React.FC<ISetUpProps> = ({
</Typography>
</Box>
<Box sx={styles.boxStyle}>
<TextField fullWidth sx={styles.textFieldStyle} placeholder="https://properlink.com" />
<TextField fullWidth sx={styles.textFieldStyle} value={lobbyState ? lobbyState.connectionLink : ''} />
<Button variant="contained" sx={styles.buttonStyle}>Copy Invite Link</Button>
</Box>
</CardContent>
Expand Down Expand Up @@ -146,6 +170,31 @@ const SetUpCard: React.FC<ISetUpProps> = ({
)}
</>
)}
{lobbyState && lobbyState.privacy === 'Private' && <>
<Box sx={styles.labelTextStyle}>
<Link href="https://www.swudb.com/" target="_blank" sx={{ color: 'lightblue' }}>
SWUDB
</Link>{' '}
or{' '}
<Link href="https://www.sw-unlimited-db.com/" target="_blank" sx={{ color: 'lightblue' }}>
SW-Unlimited-DB
</Link>{' '}
Deck Link{' '}
<Typography variant="body1" sx={styles.labelTextStyleSecondary}>
(use the URL or &apos;Deck Link&apos; button)
</Typography>
</Box>
<StyledTextField
type="url"
value={deckLink}
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setDeckLink(e.target.value)
}
/>
<Button type="button" onClick={handleOnChangeDeck} variant="contained" sx={styles.submitButtonStyle}>
Change Deck
</Button>
</>}
</Card>
);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,14 @@ import {
} from '@mui/material';
import StyledTextField from '../_styledcomponents/StyledTextField/StyledTextField';
import { usePathname, useRouter } from 'next/navigation';
import { updateIdsWithMapping, mapIdToInternalName, transformDeckWithCardData } from '@/app/_utils/s3Utils';
import { useUser } from '@/app/_contexts/User.context';
import { fetchDeckData } from '@/app/_utils/fetchDeckData';

interface ICreateGameFormProps {
format?: string | null;
setFormat?: (format: string) => void;
}

interface IDeckMetadata {
name: string;
author: string;
}

interface IDeckCard {
id: string;
count: number;
}

interface IDeckData {
metadata: IDeckMetadata;
leader: IDeckCard;
secondleader: IDeckCard | null;
base: IDeckCard;
deck: IDeckCard[];
sideboard: IDeckCard[];
}

const deckOptions: string[] = [
'Order66',
'ThisIsTheWay',
Expand All @@ -62,52 +43,10 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
const [favouriteDeck, setFavouriteDeck] = useState<string>('');
const [deckLink, setDeckLink] = useState<string>('');
const [saveDeck, setSaveDeck] = useState<boolean>(false);
// let [deckData, setDeckData] = useState<DeckData | null>(null); Because of Async this won't set in the correct timeframe

// Additional State for Non-Creategame Path
const [gameName, setGameName] = useState<string>('');
const [privacy, setPrivacy] = useState<string>('Public');

const fetchDeckData = async (deckLink: string) => {
try {
const response = await fetch(
`/api/swudbdeck?deckLink=${encodeURIComponent(deckLink)}`
);
if (!response.ok) {
throw new Error(`Failed to fetch deck: ${response.statusText}`);
}

const data: IDeckData = await response.json();

// Fetch setToId mapping from the s3bucket endpoint
const setCodeMapping = await fetch('/api/s3bucket?jsonFile=_setCodeMap.json'); // Adjust to your actual endpoint if different
if (!setCodeMapping.ok) {
throw new Error('Failed to fetch card mapping');
}

const jsonData = await setCodeMapping.json();
const deckWithIds = updateIdsWithMapping(data, jsonData);

// Fetch codeToInternalname mapping
const codeInternalnameMapping = await fetch('/api/s3bucket?jsonFile=_cardMap.json'); // Adjust to your actual endpoint if different
if (!codeInternalnameMapping.ok) {
throw new Error('Failed to fetch card mapping');
}

const codeInternalnameJson = await codeInternalnameMapping.json();
const deckWithInternalNames = mapIdToInternalName(codeInternalnameJson, deckWithIds)

// Fetch internalNameToCardMapping
const finalDeckForm = await transformDeckWithCardData(deckWithInternalNames);
return finalDeckForm
} catch (error) {
if (error instanceof Error) {
console.error('Error fetching deck:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
};
const [privacy, setPrivacy] = useState<string>(user ? 'Public' : 'Private');

// Handle Create Game Submission
const handleCreateGameSubmit = async (event: FormEvent<HTMLFormElement>) => {
Expand All @@ -121,7 +60,8 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
try {
const payload = {
user: user,
deck: deckData
deck: deckData,
privacy: privacy
};
const response = await fetch('http://localhost:9500/api/create-lobby',
{
Expand All @@ -136,7 +76,12 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
if (!response.ok) {
throw new Error('Failed to create game');
}

const responseJson = await response.json();
console.log('Response data:', responseJson);
// Store unknownUserId in local storage (so we can retrieve it in GameContext)
if(privacy === 'Private') {
localStorage.setItem('unknownUserId', responseJson.newUserId);
}
router.push('/lobby');
} catch (error) {
console.error(error);
Expand Down Expand Up @@ -191,7 +136,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
</Typography>
<form onSubmit={handleCreateGameSubmit}>
{/* Favourite Decks Input */}
<FormControl fullWidth sx={formControlStyle}>
{user && <FormControl fullWidth sx={formControlStyle}>
<Typography variant="body1" sx={labelTextStyle}>Favourite Decks</Typography>
<StyledTextField
select
Expand All @@ -208,7 +153,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
))}
</StyledTextField>
</FormControl>

}
{/* SWUDB Deck Link Input */}
<FormControl fullWidth sx={{ mb: 0 }}>
<Box sx={labelTextStyle}>
Expand All @@ -234,7 +179,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
</FormControl>

{/* Save Deck To Favourites Checkbox */}
<FormControlLabel
{user && <FormControlLabel
sx={{ mb: '1rem' }}
control={
<Checkbox
Expand All @@ -252,6 +197,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
</Typography>
}
/>
}

{/* Additional Fields for Non-Creategame Path */}
{!isCreateGamePath && (
Expand Down Expand Up @@ -289,7 +235,9 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
))}
</StyledTextField>
</FormControl>

<Typography>
Log In to be able to create public games or join a quick game.
</Typography>
{/* Privacy Selection */}
<FormControl component="fieldset" sx={formControlStyle}>
<RadioGroup
Expand All @@ -300,7 +248,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
value: string
) => setPrivacy(value)}
>
<FormControlLabel
{user && <FormControlLabel
value="Public"
control={<Radio sx={checkboxStyle} />}
label={
Expand All @@ -309,6 +257,7 @@ const CreateGameForm: React.FC<ICreateGameFormProps> = ({
</Typography>
}
/>
}
<FormControlLabel
value="Private"
control={<Radio sx={checkboxStyle} />}
Expand Down
Loading

0 comments on commit e718d05

Please sign in to comment.