fork/replay-manager-for-slippi

git clone https://git.julia.blue/fork/replay-manager-for-slippi

Nicoletdisambiguate context (sgg) `id` vs `internalId`e87008e

2.4.1
37.7 KiB1112 linesraw
1import { MatchResult, SlotState } from '@parry-gg/client';
2import { Backup, Report, VideogameAssetOff } from '@mui/icons-material';
3import {
4  Avatar,
5  Box,
6  Button,
7  CircularProgress,
8  Dialog,
9  DialogActions,
10  DialogContent,
11  DialogContentText,
12  DialogTitle,
13  Divider,
14  IconButton,
15  Stack,
16  Tooltip,
17  Typography,
18} from '@mui/material';
19import { MouseEventHandler, useEffect, useState } from 'react';
20import styled from '@emotion/styled';
21import {
22  ChallongeMatchItem,
23  EnforcerSetting,
24  EnforceState,
25  EnforceStatus,
26  Id,
27  Mode,
28  Player,
29  Replay,
30  ReportSettings,
31  Set,
32  StartggGame,
33  StartggGameSelection,
34  StartggSet,
35  State,
36  Stream,
37} from '../common/types';
38import {
39  characterNames,
40  characterStartggIds,
41  isValidCharacter,
42  stageNames,
43  stageStartggIds,
44  startggCharacterIds,
45  startggStageIds,
46} from '../common/constants';
47import LabeledCheckbox from './LabeledCheckbox';
48import getCharacterIcon from './getCharacterIcon';
49import { assertInteger, assertString } from '../common/asserts';
50
51const bgColor = 'rgba(34, 178, 76, 0.2)';
52
53function getCharacterIconInner(
54  characterId: number | undefined,
55  costumeIndex?: number,
56) {
57  if (characterId === undefined) {
58    return getCharacterIcon(31, 0);
59  }
60  if (costumeIndex === undefined) {
61    return getCharacterIcon(characterId, 0);
62  }
63  return getCharacterIcon(characterId, costumeIndex);
64}
65
66const EntrantSection = styled(Stack)`
67  align-items: center;
68  width: 50%;
69`;
70
71const EntrantText = styled(Stack)`
72  margin: 0 4px;
73  min-width: 0;
74`;
75
76const EntrantScore = styled(EntrantText)`
77  width: 16px;
78`;
79
80const Name = styled.div`
81  overflow-x: hidden;
82  text-overflow: ellipsis;
83  white-space: nowrap;
84`;
85
86function isValid(player: Player) {
87  return player.playerType === 0 || player.playerType === 1;
88}
89
90function setAndReplaysValid(selectedReplays: Replay[], set: Set, mode: Mode) {
91  if (selectedReplays.length === 0) {
92    return { valid: false, reason: 'No replays selected' };
93  }
94  if (mode === Mode.CHALLONGE && set.state === State.COMPLETED) {
95    return { valid: false, reason: 'Set already completed' };
96  }
97
98  let reason = '';
99  const valid = selectedReplays.every((replay, i) => {
100    if (set.id === 0) {
101      if (!reason) {
102        reason = 'No set selected';
103      }
104      return false;
105    }
106    if (Number.isInteger(set.id) && (set.id as number) < 0) {
107      if (!reason) {
108        reason = 'Tiebreaker sets cannot be reported';
109      }
110      return false;
111    }
112
113    const validPlayers = replay.players.filter(isValid);
114    if (
115      validPlayers.length !==
116      set.entrant1Participants.length + set.entrant2Participants.length
117    ) {
118      if (!reason) {
119        reason = `Game ${i + 1} has wrong number of players`;
120      }
121      return false;
122    }
123    if (!(validPlayers.find((player) => player.isWinner) || replay.timeout)) {
124      if (!reason) {
125        reason = `Game ${i + 1} does not have a winner`;
126      }
127      return false;
128    }
129    if (!validPlayers.every((player) => player.playerOverrides.entrantId)) {
130      if (!reason) {
131        reason = `Game ${i + 1} does not have all players assigned`;
132      }
133      return false;
134    }
135    return true;
136  });
137
138  return { valid, reason };
139}
140
141function getScoresAndWinnerId(selectedReplays: Replay[]) {
142  let gameCount = 0;
143  const gameWins = new Map<Id, number>();
144  let leaderId: Id = 0;
145  let leaderWins = 0;
146  selectedReplays.forEach((replay) => {
147    const gameWinnerId = replay.players
148      .filter(isValid)
149      .find((player) => player.isWinner)?.playerOverrides.entrantId;
150    if (!gameWinnerId) {
151      return;
152    }
153
154    const n = (gameWins.get(gameWinnerId) || 0) + 1;
155    if (n > leaderWins) {
156      leaderWins = n;
157      leaderId = gameWinnerId;
158    }
159    gameCount += 1;
160    gameWins.set(gameWinnerId, n);
161  });
162
163  return {
164    scores: gameWins,
165    winnerId: leaderWins / gameCount > 0.5 ? leaderId : 0,
166  };
167}
168
169function getDisplayNameFromPlayer(player?: Player) {
170  return player?.playerOverrides.displayName || player?.displayName;
171}
172
173function ReportButton({
174  disabled,
175  elevate,
176  onClick,
177}: {
178  disabled?: boolean;
179  elevate: boolean;
180  onClick?: MouseEventHandler<HTMLButtonElement>;
181}) {
182  return (
183    <Button
184      disabled={disabled}
185      endIcon={<Backup />}
186      onClick={onClick}
187      size="small"
188      variant="contained"
189      sx={{
190        zIndex: (theme) => (elevate ? theme.zIndex.drawer + 2 : undefined),
191      }}
192    >
193      Report
194    </Button>
195  );
196}
197ReportButton.defaultProps = {
198  disabled: false,
199  onClick: undefined,
200};
201
202export default function SetControls({
203  copyReplays,
204  deleteReplays,
205  reportChallongeSet,
206  reportStartggSet,
207  reportParryggSet,
208  reportOfflineModeSet,
209  setReportSettings,
210  resetGuide,
211  mode,
212  isCopying,
213  copyDisabled,
214  isDeleting,
215  dqId,
216  hasRemainingReplays,
217  reportSettings,
218  selectedReplays,
219  set,
220  elevate,
221  enforcerVersion,
222  enforcerSetting,
223  smuggleCostumeIndex,
224  wouldDeleteCopyDir,
225  replayLoadCount,
226  undoSubdir,
227}: {
228  copyReplays: (
229    updatedSetFields?: {
230      id: Id;
231      sggId: number | null;
232      completedAtMs: number;
233      stream: Stream | null;
234    },
235    violators?: {
236      checkNames: Map<string, boolean>;
237      displayName: string;
238      entrantId: Id;
239    }[],
240  ) => Promise<void>;
241  deleteReplays: () => Promise<void>;
242  reportChallongeSet: (
243    matchId: string,
244    items: ChallongeMatchItem[],
245  ) => Promise<Set>;
246  reportStartggSet: (
247    set: StartggSet,
248    originalSet: Set,
249  ) => Promise<Set | undefined>;
250  reportParryggSet: (
251    result: MatchResult.AsObject,
252    originalSet: Set,
253  ) => Promise<Set | undefined>;
254  reportOfflineModeSet: (set: StartggSet) => Promise<Set>;
255  setReportSettings: (newReportSettings: ReportSettings) => Promise<void>;
256  resetGuide: () => void;
257  mode: Mode;
258  isCopying: boolean;
259  copyDisabled: boolean;
260  isDeleting: boolean;
261  dqId: Id;
262  hasRemainingReplays: boolean;
263  reportSettings: ReportSettings;
264  selectedReplays: Replay[];
265  set: Set;
266  elevate: boolean;
267  enforcerVersion: string;
268  enforcerSetting: EnforcerSetting;
269  smuggleCostumeIndex: boolean;
270  wouldDeleteCopyDir: boolean;
271  replayLoadCount: number;
272  undoSubdir: string;
273}) {
274  const [open, setOpen] = useState(false);
275  const [reporting, setReporting] = useState(false);
276  const [reportError, setReportError] = useState('');
277  const [reportErrorOpen, setReportErrorOpen] = useState(false);
278  const [startggSet, setStartggSet] = useState<StartggSet>({
279    setId: set.id,
280    winnerId: 0,
281    isDQ: false,
282    gameData: [],
283  });
284  const [challongeMatchItems, setChallongeMatchItems] = useState<
285    ChallongeMatchItem[]
286  >([
287    {
288      participant_id: '',
289      score_set: '',
290      rank: 0,
291      advancing: false,
292    },
293    {
294      participant_id: '',
295      score_set: '',
296      rank: 0,
297      advancing: false,
298    },
299  ]);
300  const [parryggMatchResult, setParryggMatchResult] =
301    useState<MatchResult.AsObject>({
302      slotsList: [
303        {
304          slot: 0,
305          score: 0,
306          state: SlotState.SLOT_STATE_NUMERIC,
307        },
308        {
309          slot: 1,
310          score: 0,
311          state: SlotState.SLOT_STATE_NUMERIC,
312        },
313      ],
314    });
315
316  const [enforcerResultOpen, setEnforcerResultOpen] = useState(false);
317  const [enforceState, setEnforceState] = useState<EnforceState>({
318    status: EnforceStatus.DONE,
319    fileNameToPlayerFailures: new Map(),
320  });
321  useEffect(() => {
322    window.electron.onEnforceState(
323      (event, newEnforceState, newReplayLoadCount) => {
324        if (newReplayLoadCount >= replayLoadCount) {
325          setEnforceState(newEnforceState);
326        }
327      },
328    );
329  }, [replayLoadCount]);
330  const selectedReplaysWithEnforceErrors =
331    enforceState.status === EnforceStatus.DONE
332      ? selectedReplays.filter((replay) =>
333          enforceState.fileNameToPlayerFailures.has(replay.fileName),
334        )
335      : [];
336  let showEnforcerPopup = false;
337  if (enforcerSetting === EnforcerSetting.POP_UP_ALL) {
338    showEnforcerPopup = selectedReplaysWithEnforceErrors.length > 0;
339  } else if (enforcerSetting === EnforcerSetting.POP_UP_GOOMWAVE) {
340    showEnforcerPopup = selectedReplaysWithEnforceErrors.some((replay) =>
341      enforceState.fileNameToPlayerFailures
342        .get(replay.fileName)!
343        .some((enforcerPlayerError) =>
344          enforcerPlayerError.checkNames.includes('GoomWave Clamping'),
345        ),
346    );
347  }
348
349  const isDq = dqId === set.entrant1Id || dqId === set.entrant2Id;
350  const validSelections = setAndReplaysValid(selectedReplays, set, mode);
351  let scores = new Map<Id, number>();
352  let winnerId: Id = 0;
353  if (validSelections.valid) {
354    ({ scores, winnerId } = getScoresAndWinnerId(selectedReplays));
355  } else if (isDq) {
356    if (dqId === set.entrant1Id) {
357      scores.set(set.entrant1Id, -1);
358      scores.set(set.entrant2Id, 0);
359      winnerId = set.entrant2Id;
360    } else {
361      scores.set(set.entrant1Id, 0);
362      scores.set(set.entrant2Id, -1);
363      winnerId = set.entrant1Id;
364    }
365  }
366
367  const entrant1SetScore = scores.get(set.entrant1Id) || 0;
368  const entrant2SetScore = scores.get(set.entrant2Id) || 0;
369
370  const getStartggSet = (): StartggSet => {
371    if (isDq) {
372      return { setId: set.id, winnerId, isDQ: true, gameData: [] };
373    }
374
375    const gameData: StartggGame[] = [];
376    selectedReplays.forEach((replay, i) => {
377      const gameWinnerId = replay.players.find((player) => player.isWinner)
378        ?.playerOverrides.entrantId;
379      if (!gameWinnerId) {
380        return;
381      }
382
383      const originalEntrant1Score = set.gameScores[i]?.entrant1Score ?? 0;
384      const originalEntrant2Score = set.gameScores[i]?.entrant2Score ?? 0;
385      let entrant1CostumeOffset = Math.floor(originalEntrant1Score / 100) * 100;
386      let entrant2CostumeOffset = Math.floor(originalEntrant2Score / 100) * 100;
387      let entrant1Stocks = originalEntrant1Score % 100;
388      let entrant2Stocks = originalEntrant2Score % 100;
389      const participantIdToSelection = new Map<Id, StartggGameSelection>();
390      const validPlayers = replay.players.filter(
391        (player) =>
392          isValid(player) && isValidCharacter(player.externalCharacterId),
393      );
394      validPlayers.forEach((player) => {
395        const { entrantId, participantId } = player.playerOverrides;
396        participantIdToSelection.set(participantId, {
397          characterId: characterStartggIds.get(player.externalCharacterId)!,
398          entrantId,
399        });
400        if (validPlayers.length === 2) {
401          if (entrantId === set.entrant1Id) {
402            if (smuggleCostumeIndex) {
403              entrant1CostumeOffset = (player.costumeIndex + 1) * 100;
404            }
405            if (player.stocksRemaining >= 0) {
406              entrant1Stocks = player.stocksRemaining;
407            }
408          } else {
409            if (smuggleCostumeIndex) {
410              entrant2CostumeOffset = (player.costumeIndex + 1) * 100;
411            }
412            if (player.stocksRemaining >= 0) {
413              entrant2Stocks = player.stocksRemaining;
414            }
415          }
416        }
417      });
418      const selections = [
419        ...set.entrant1Participants.map(
420          (participant) => participantIdToSelection.get(participant.id)!,
421        ),
422        ...set.entrant2Participants.map(
423          (participant) => participantIdToSelection.get(participant.id)!,
424        ),
425      ];
426      gameData.push({
427        entrant1Score: entrant1CostumeOffset + entrant1Stocks,
428        entrant2Score: entrant2CostumeOffset + entrant2Stocks,
429        gameNum: i + 1,
430        stageId: stageStartggIds.get(replay.stageId),
431        selections,
432        winnerId: assertInteger(gameWinnerId),
433      });
434    });
435    return { setId: set.id, winnerId, isDQ: false, gameData };
436  };
437
438  const getChallongeMatchItems = (): ChallongeMatchItem[] => [
439    {
440      participant_id: set.entrant1Id.toString(10),
441      score_set: entrant1SetScore.toString(10),
442      rank: winnerId === set.entrant1Id ? 1 : 2,
443      advancing: winnerId === set.entrant1Id,
444    },
445    {
446      participant_id: set.entrant2Id.toString(10),
447      score_set: entrant2SetScore.toString(10),
448      rank: winnerId === set.entrant2Id ? 1 : 2,
449      advancing: winnerId === set.entrant2Id,
450    },
451  ];
452
453  const getMatchResult = (): MatchResult.AsObject => {
454    const entrant1Dq = isDq && dqId === set.entrant1Id;
455    const entrant2Dq = isDq && dqId === set.entrant2Id;
456
457    return {
458      slotsList: [
459        {
460          slot: 0,
461          score: entrant1Dq ? 0 : entrant1SetScore,
462          state: entrant1Dq
463            ? SlotState.SLOT_STATE_DQ
464            : SlotState.SLOT_STATE_NUMERIC,
465        },
466        {
467          slot: 1,
468          score: entrant2Dq ? 0 : entrant2SetScore,
469          state: entrant2Dq
470            ? SlotState.SLOT_STATE_DQ
471            : SlotState.SLOT_STATE_NUMERIC,
472        },
473      ],
474    };
475  };
476
477  let deleteOverrideReason = '';
478  if (set.fullRoundText === 'Grand Final' && hasRemainingReplays) {
479    deleteOverrideReason = 'possible Grand Finals Reset replays detected';
480  } else if (wouldDeleteCopyDir) {
481    deleteOverrideReason = 'would delete replays in copy folder';
482  }
483
484  let reportCopyDeleteIntent = 'Report';
485  if (reportSettings.alsoCopy || undoSubdir) {
486    reportCopyDeleteIntent += ', Copy';
487  }
488  if (
489    (reportSettings.alsoCopy &&
490      reportSettings.alsoDelete &&
491      deleteOverrideReason.length === 0) ||
492    undoSubdir
493  ) {
494    reportCopyDeleteIntent += ', Delete';
495  }
496
497  let reportCopyDeleteButton = reportCopyDeleteIntent;
498  if (enforceState.status === EnforceStatus.PENDING) {
499    reportCopyDeleteButton = 'Checking with SLP Enforcer';
500  } else if ((reportSettings.alsoCopy || undoSubdir) && copyDisabled) {
501    reportCopyDeleteButton = 'Copy destination not set';
502  } else if ((reportSettings.alsoCopy || undoSubdir) && isCopying) {
503    reportCopyDeleteButton = 'Copying';
504  } else if ((reportSettings.alsoDelete || undoSubdir) && isDeleting) {
505    reportCopyDeleteButton = 'Deleting';
506  } else if (reporting) {
507    reportCopyDeleteButton = 'Reporting';
508  }
509
510  return (
511    <>
512      {validSelections.valid && (winnerId || isDq) ? (
513        <ReportButton
514          elevate={elevate}
515          onClick={() => {
516            if (mode === Mode.STARTGG || mode === Mode.OFFLINE_MODE) {
517              setStartggSet(getStartggSet());
518            } else if (mode === Mode.CHALLONGE) {
519              setChallongeMatchItems(getChallongeMatchItems());
520            } else if (mode === Mode.PARRYGG) {
521              setParryggMatchResult(getMatchResult());
522            }
523            if (
524              (selectedReplaysWithEnforceErrors.length > 0 &&
525                showEnforcerPopup) ||
526              enforceState.status === EnforceStatus.ERROR
527            ) {
528              setEnforcerResultOpen(true);
529            }
530            setOpen(true);
531          }}
532        />
533      ) : (
534        <Tooltip
535          arrow
536          title={!validSelections.valid ? validSelections.reason : 'No winner'}
537        >
538          <div>
539            <ReportButton disabled elevate={elevate} />
540          </div>
541        </Tooltip>
542      )}
543      <Dialog
544        open={open}
545        onClose={() => {
546          setOpen(false);
547          setStartggSet({
548            setId: set.id,
549            winnerId: 0,
550            isDQ: false,
551            gameData: [],
552          });
553        }}
554      >
555        <DialogTitle typography="body1">
556          Report set on {mode === Mode.STARTGG && 'start.gg'}
557          {mode === Mode.CHALLONGE && 'Challonge'}
558          {mode === Mode.PARRYGG && 'parry.gg'}
559          {mode === Mode.OFFLINE_MODE && 'Offline Mode'}
560        </DialogTitle>
561        <DialogContent sx={{ width: '500px' }}>
562          <Stack>
563            <Box sx={{ typography: 'caption' }} textAlign="center">
564              {set.fullRoundText}
565            </Box>
566            <Stack
567              alignItems="center"
568              direction="row"
569              sx={{ typography: 'h5' }}
570            >
571              <EntrantSection
572                borderRight={1}
573                direction="row-reverse"
574                style={{
575                  backgroundColor:
576                    set.entrant1Id === winnerId ? bgColor : undefined,
577                }}
578              >
579                <Box marginRight="8px" width="24px" textAlign="right">
580                  {entrant1SetScore}
581                </Box>
582                <Stack textAlign="right">
583                  <Name>{set.entrant1Participants[0].displayName}</Name>
584                  {set.entrant1Participants.length > 1 && (
585                    <Name>{set.entrant1Participants[1].displayName}</Name>
586                  )}
587                </Stack>
588              </EntrantSection>
589              <EntrantSection
590                borderLeft={1}
591                direction="row"
592                style={{
593                  backgroundColor:
594                    set.entrant2Id === winnerId ? bgColor : undefined,
595                }}
596              >
597                <Box marginLeft="8px" width="24px">
598                  {entrant2SetScore}
599                </Box>
600                <Stack>
601                  <Name>{set.entrant2Participants[0].displayName}</Name>
602                  {set.entrant2Participants.length > 1 && (
603                    <Name>{set.entrant2Participants[1].displayName}</Name>
604                  )}
605                </Stack>
606              </EntrantSection>
607            </Stack>
608          </Stack>
609          <Divider sx={{ marginTop: '16px' }} />
610          <Stack flexGrow={1}>
611            {(mode === Mode.STARTGG || mode === Mode.OFFLINE_MODE) &&
612              startggSet.gameData.map((gameData) => (
613                <Stack key={gameData.gameNum} marginTop="8px">
614                  {gameData.stageId && (
615                    <Box sx={{ typography: 'caption' }} textAlign="center">
616                      {stageNames.get(startggStageIds.get(gameData.stageId)!)}
617                    </Box>
618                  )}
619                  <Stack direction="row" sx={{ typography: 'body2' }}>
620                    <EntrantSection borderRight={1} direction="row-reverse">
621                      <Stack
622                        alignItems="center"
623                        direction="row-reverse"
624                        paddingTop="4px"
625                        paddingBottom="4px"
626                        paddingLeft={
627                          set.entrant1Participants.length === 1
628                            ? '4px'
629                            : undefined
630                        }
631                        style={{
632                          backgroundColor:
633                            set.entrant1Id === gameData.winnerId
634                              ? bgColor
635                              : undefined,
636                        }}
637                      >
638                        <EntrantScore textAlign="right">
639                          {set.entrant1Id === gameData.winnerId && 'W'}
640                        </EntrantScore>
641                        {set.entrant1Participants.length === 1 && (
642                          <Avatar
643                            alt={characterNames.get(
644                              startggCharacterIds.get(
645                                gameData.selections[0].characterId,
646                              )!,
647                            )}
648                            src={getCharacterIconInner(
649                              startggCharacterIds.get(
650                                gameData.selections[0].characterId,
651                              ),
652                              gameData.entrant1Score >= 100
653                                ? Math.floor(gameData.entrant1Score / 100) - 1
654                                : undefined,
655                            )}
656                            sx={{ height: 24, width: 24 }}
657                            variant="square"
658                          />
659                        )}
660                        {set.entrant1Participants.length === 2 && (
661                          <>
662                            <Avatar
663                              alt={characterNames.get(
664                                startggCharacterIds.get(
665                                  gameData.selections[1].characterId,
666                                )!,
667                              )}
668                              src={getCharacterIconInner(
669                                startggCharacterIds.get(
670                                  gameData.selections[1].characterId,
671                                ),
672                              )}
673                              sx={{ height: 24, width: 24 }}
674                              variant="square"
675                            />
676                            <Avatar
677                              alt={characterNames.get(
678                                startggCharacterIds.get(
679                                  gameData.selections[0].characterId,
680                                )!,
681                              )}
682                              src={getCharacterIconInner(
683                                startggCharacterIds.get(
684                                  gameData.selections[0].characterId,
685                                ),
686                              )}
687                              sx={{ height: 24, width: 24 }}
688                              variant="square"
689                            />
690                          </>
691                        )}
692                      </Stack>
693                      {set.entrant1Participants.length === 1 &&
694                        set.entrant1Id === gameData.winnerId &&
695                        gameData.entrant1Score % 100 && (
696                          <Tooltip
697                            arrow
698                            placement="left"
699                            title={`${gameData.entrant1Score % 100} stock`}
700                          >
701                            <Stack
702                              alignItems="end"
703                              direction="row"
704                              gap="1px"
705                              marginRight="8px"
706                              height="100%"
707                            >
708                              {[
709                                ...Array(gameData.entrant1Score % 100).keys(),
710                              ].map(() => (
711                                <Avatar
712                                  src={getCharacterIconInner(
713                                    startggCharacterIds.get(
714                                      gameData.selections[0].characterId,
715                                    ),
716                                    gameData.entrant1Score >= 100
717                                      ? Math.floor(
718                                          gameData.entrant1Score / 100,
719                                        ) - 1
720                                      : undefined,
721                                  )}
722                                  sx={{ height: 12, width: 12 }}
723                                  variant="square"
724                                />
725                              ))}
726                            </Stack>
727                          </Tooltip>
728                        )}
729                    </EntrantSection>
730                    <EntrantSection borderLeft={1} direction="row">
731                      <Stack
732                        alignItems="center"
733                        direction="row"
734                        paddingTop="4px"
735                        paddingBottom="4px"
736                        paddingRight={
737                          set.entrant2Participants.length === 1
738                            ? '4px'
739                            : undefined
740                        }
741                        style={{
742                          backgroundColor:
743                            set.entrant2Id === gameData.winnerId
744                              ? bgColor
745                              : undefined,
746                        }}
747                      >
748                        <EntrantScore>
749                          {set.entrant2Id === gameData.winnerId && 'W'}
750                        </EntrantScore>
751                        {set.entrant2Participants.length === 1 && (
752                          <Avatar
753                            alt={characterNames.get(
754                              startggCharacterIds.get(
755                                gameData.selections[1].characterId,
756                              )!,
757                            )}
758                            src={getCharacterIconInner(
759                              startggCharacterIds.get(
760                                gameData.selections[1].characterId,
761                              ),
762                              gameData.entrant2Score >= 100
763                                ? Math.floor(gameData.entrant2Score / 100) - 1
764                                : undefined,
765                            )}
766                            sx={{ height: 24, width: 24 }}
767                            variant="square"
768                          />
769                        )}
770                        {set.entrant2Participants.length === 2 && (
771                          <>
772                            <Avatar
773                              alt={characterNames.get(
774                                startggCharacterIds.get(
775                                  gameData.selections[
776                                    set.entrant1Participants.length
777                                  ].characterId,
778                                )!,
779                              )}
780                              src={getCharacterIconInner(
781                                startggCharacterIds.get(
782                                  gameData.selections[
783                                    set.entrant1Participants.length
784                                  ].characterId,
785                                ),
786                              )}
787                              sx={{ height: 24, width: 24 }}
788                              variant="square"
789                            />
790                            <Avatar
791                              alt={characterNames.get(
792                                startggCharacterIds.get(
793                                  gameData.selections[
794                                    set.entrant1Participants.length + 1
795                                  ].characterId,
796                                )!,
797                              )}
798                              src={getCharacterIconInner(
799                                startggCharacterIds.get(
800                                  gameData.selections[
801                                    set.entrant1Participants.length + 1
802                                  ].characterId,
803                                ),
804                              )}
805                              sx={{ height: 24, width: 24 }}
806                              variant="square"
807                            />
808                          </>
809                        )}
810                      </Stack>
811                      {set.entrant2Participants.length === 1 &&
812                        set.entrant2Id === gameData.winnerId &&
813                        gameData.entrant2Score % 100 && (
814                          <Tooltip
815                            arrow
816                            placement="right"
817                            title={`${gameData.entrant2Score % 100} stock`}
818                          >
819                            <Stack
820                              alignItems="end"
821                              direction="row"
822                              gap="1px"
823                              marginLeft="8px"
824                              height="100%"
825                            >
826                              {[
827                                ...Array(gameData.entrant2Score % 100).keys(),
828                              ].map(() => (
829                                <Avatar
830                                  src={getCharacterIconInner(
831                                    startggCharacterIds.get(
832                                      gameData.selections[1].characterId,
833                                    ),
834                                    gameData.entrant2Score >= 100
835                                      ? Math.floor(
836                                          gameData.entrant2Score / 100,
837                                        ) - 1
838                                      : undefined,
839                                  )}
840                                  sx={{ height: 12, width: 12 }}
841                                  variant="square"
842                                />
843                              ))}
844                            </Stack>
845                          </Tooltip>
846                        )}
847                    </EntrantSection>
848                  </Stack>
849                </Stack>
850              ))}
851          </Stack>
852          <Divider sx={{ marginTop: '8px' }} />
853          <Stack justifyContent="flex-end">
854            <LabeledCheckbox
855              checked={reportSettings.alsoCopy || undoSubdir.length > 0}
856              disabled={undoSubdir.length > 0}
857              label="Copy replays after reporting"
858              labelPlacement="start"
859              set={(checked: boolean) => {
860                const newReportSettings = { ...reportSettings };
861                newReportSettings.alsoCopy = checked;
862                setReportSettings(newReportSettings);
863              }}
864            />
865            <LabeledCheckbox
866              checked={reportSettings.alsoDelete || undoSubdir.length > 0}
867              disabled={
868                !reportSettings.alsoCopy ||
869                deleteOverrideReason.length > 0 ||
870                undoSubdir.length > 0
871              }
872              label={
873                deleteOverrideReason.length > 0
874                  ? `Delete disabled, ${deleteOverrideReason}`
875                  : '...then delete originals and eject'
876              }
877              labelPlacement="start"
878              set={(checked: boolean) => {
879                const newReportSettings = { ...reportSettings };
880                newReportSettings.alsoDelete = checked;
881                setReportSettings(newReportSettings);
882              }}
883            />
884          </Stack>
885        </DialogContent>
886        <DialogActions>
887          {enforceState.status === EnforceStatus.ERROR && (
888            <Tooltip arrow placement="top" title="SLP Enforcer Failure">
889              <IconButton
890                onClick={() => {
891                  setEnforcerResultOpen(true);
892                }}
893              >
894                <Report />
895              </IconButton>
896            </Tooltip>
897          )}
898          {selectedReplaysWithEnforceErrors.length > 0 && (
899            <Tooltip
900              arrow
901              placement="top"
902              title="Controller Ruleset Violation Detected"
903            >
904              <IconButton
905                onClick={() => {
906                  setEnforcerResultOpen(true);
907                }}
908              >
909                <VideogameAssetOff />
910              </IconButton>
911            </Tooltip>
912          )}
913          <Button
914            disabled={
915              reporting ||
916              (reportSettings.alsoCopy && isCopying) ||
917              (reportSettings.alsoCopy && copyDisabled) ||
918              enforceState.status === EnforceStatus.PENDING
919            }
920            endIcon={
921              reporting || enforceState.status === EnforceStatus.PENDING ? (
922                <CircularProgress size="24px" />
923              ) : (
924                <Backup />
925              )
926            }
927            onClick={async () => {
928              setReporting(true);
929              try {
930                let updatedSet: Set | undefined;
931                if (mode === Mode.STARTGG) {
932                  updatedSet = await reportStartggSet(startggSet, set);
933                } else if (mode === Mode.CHALLONGE) {
934                  updatedSet = await reportChallongeSet(
935                    assertString(set.id),
936                    challongeMatchItems,
937                  );
938                } else if (mode === Mode.PARRYGG) {
939                  updatedSet = await reportParryggSet(parryggMatchResult, set);
940                } else if (mode === Mode.OFFLINE_MODE) {
941                  updatedSet = await reportOfflineModeSet(startggSet);
942                }
943                if (reportSettings.alsoCopy || undoSubdir) {
944                  const entrantIdToDisplayNameAndCheckNames = new Map<
945                    Id,
946                    { checkNames: Map<string, boolean>; displayName: string }
947                  >();
948                  selectedReplaysWithEnforceErrors.forEach((replay) => {
949                    enforceState.fileNameToPlayerFailures
950                      .get(replay.fileName)!
951                      .forEach((playerFailure) => {
952                        const failurePlayer = replay.players.find(
953                          (player) => player.port === playerFailure.port,
954                        )!;
955                        const displayName =
956                          failurePlayer.playerOverrides.displayName ||
957                          failurePlayer.displayName;
958                        const { entrantId } = failurePlayer.playerOverrides;
959                        if (entrantId) {
960                          if (
961                            entrantIdToDisplayNameAndCheckNames.has(entrantId)
962                          ) {
963                            const { checkNames } =
964                              entrantIdToDisplayNameAndCheckNames.get(
965                                entrantId,
966                              )!;
967                            playerFailure.checkNames.forEach((checkName) => {
968                              checkNames.set(checkName, true);
969                            });
970                          } else {
971                            entrantIdToDisplayNameAndCheckNames.set(entrantId, {
972                              checkNames: new Map(
973                                playerFailure.checkNames.map((checkName) => [
974                                  checkName,
975                                  true,
976                                ]),
977                              ),
978                              displayName,
979                            });
980                          }
981                        }
982                      });
983                  });
984                  await copyReplays(
985                    updatedSet
986                      ? {
987                          id: updatedSet.id,
988                          sggId: updatedSet.sggId,
989                          completedAtMs: updatedSet.completedAtMs,
990                          stream: updatedSet.stream,
991                        }
992                      : undefined,
993                    Array.from(entrantIdToDisplayNameAndCheckNames).map(
994                      ([entrantId, { checkNames, displayName }]) => ({
995                        checkNames,
996                        displayName,
997                        entrantId,
998                      }),
999                    ),
1000                  );
1001                }
1002                if (
1003                  (reportSettings.alsoCopy &&
1004                    reportSettings.alsoDelete &&
1005                    deleteOverrideReason.length === 0) ||
1006                  undoSubdir
1007                ) {
1008                  await deleteReplays();
1009                }
1010                setOpen(false);
1011                setStartggSet({
1012                  setId: set.id,
1013                  winnerId: 0,
1014                  isDQ: false,
1015                  gameData: [],
1016                });
1017                resetGuide();
1018              } catch (e: any) {
1019                const message = e instanceof Error ? e.message : e;
1020                setReportError(message);
1021                setReportErrorOpen(true);
1022              } finally {
1023                setReporting(false);
1024              }
1025            }}
1026            variant="contained"
1027          >
1028            {reportCopyDeleteButton}
1029          </Button>
1030        </DialogActions>
1031      </Dialog>
1032      <Dialog
1033        open={reportErrorOpen}
1034        onClose={() => {
1035          setReportErrorOpen(false);
1036          setReportError('');
1037        }}
1038      >
1039        <DialogTitle>{reportCopyDeleteIntent} error!</DialogTitle>
1040        <DialogContent>
1041          <DialogContentText>{reportError}</DialogContentText>
1042        </DialogContent>
1043        <DialogActions>
1044          <Button
1045            onClick={() => {
1046              setReportErrorOpen(false);
1047              setReportError('');
1048            }}
1049          >
1050            Close
1051          </Button>
1052        </DialogActions>
1053      </Dialog>
1054      <Dialog
1055        open={enforcerResultOpen}
1056        onClose={() => {
1057          setEnforcerResultOpen(false);
1058        }}
1059      >
1060        <Stack
1061          alignItems="center"
1062          direction="row"
1063          justifyContent="space-between"
1064          marginRight="24px"
1065        >
1066          <DialogTitle>
1067            {enforceState.status === EnforceStatus.DONE &&
1068              'Controller Ruleset Violation Detected'}
1069            {enforceState.status === EnforceStatus.ERROR &&
1070              'SLP Enforcer Failure'}
1071          </DialogTitle>
1072          <Typography variant="caption">
1073            SLP Enforcer version {enforcerVersion}
1074          </Typography>
1075        </Stack>
1076        <DialogContent sx={{ width: '500px' }}>
1077          {enforceState.status === EnforceStatus.DONE && (
1078            <Stack spacing="8px">
1079              {selectedReplaysWithEnforceErrors.map((selectedReplay) => (
1080                <Box key={selectedReplay.fileName}>
1081                  <Box typography="caption">
1082                    {stageNames.get(selectedReplay.stageId)}
1083                  </Box>
1084                  {enforceState.fileNameToPlayerFailures
1085                    .get(selectedReplay.fileName)!
1086                    .map((enforcePlayerFailure) => (
1087                      <Box key={enforcePlayerFailure.port} typography="body2">
1088                        {getDisplayNameFromPlayer(
1089                          selectedReplay.players.find(
1090                            (player) =>
1091                              player.port === enforcePlayerFailure.port,
1092                          ),
1093                        )}
1094                        : {enforcePlayerFailure.checkNames.join(', ')}
1095                      </Box>
1096                    ))}
1097                </Box>
1098              ))}
1099            </Stack>
1100          )}
1101          {enforceState.status === EnforceStatus.ERROR && (
1102            <DialogContentText>
1103              {enforceState.reason instanceof Error
1104                ? enforceState.reason.message
1105                : enforceState.reason.toString()}
1106            </DialogContentText>
1107          )}
1108        </DialogContent>
1109      </Dialog>
1110    </>
1111  );
1112}