de.pewpewproject.lasertag.networking.client.callbacks.GameStatisticsIncomingCallback   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 96
rs 10
c 0
b 0
f 0
wmc 7

1 Method

Rating   Name   Duplication   Size   Complexity  
B receive(MinecraftClient,ClientPlayNetworkHandler,PacketByteBuf,PacketSender) 0 95 7
1
package de.pewpewproject.lasertag.networking.client.callbacks;
2
3
import com.google.gson.Gson;
4
import de.pewpewproject.lasertag.LasertagMod;
5
import de.pewpewproject.lasertag.common.util.ThreadUtil;
6
import de.pewpewproject.lasertag.lasertaggame.settings.SettingDescription;
7
import de.pewpewproject.lasertag.lasertaggame.statistics.GameStats;
8
import de.pewpewproject.lasertag.lasertaggame.statistics.WebStatisticsVisualizer;
9
import de.pewpewproject.lasertag.resource.ResourceManagers;
10
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
11
import net.fabricmc.fabric.api.networking.v1.PacketSender;
12
import net.mightypork.rpack.utils.DesktopApi;
13
import net.minecraft.client.MinecraftClient;
14
import net.minecraft.client.network.ClientPlayNetworkHandler;
15
import net.minecraft.network.PacketByteBuf;
16
import net.minecraft.text.Style;
17
import net.minecraft.text.Text;
18
import net.minecraft.util.Formatting;
19
20
import java.util.concurrent.TimeUnit;
21
22
/**
23
 * Callback to handle the game statistics incoming network event
24
 *
25
 * @author Étienne Muser
26
 */
27
public class GameStatisticsIncomingCallback implements ClientPlayNetworking.PlayChannelHandler {
28
    @Override
29
    public void receive(MinecraftClient client, ClientPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {
30
31
        try {
32
33
            // Get the managers
34
            var gameManager = client.world.getClientLasertagManager();
35
            var uiState = gameManager.getSyncedState().getUIState();
36
            var settingManager = gameManager.getSettingsManager();
37
            var teamsConfigState = gameManager.getSyncedState().getTeamsConfigState();
38
            var gameModeManager = gameManager.getGameModeManager();
39
40
            // Read from buffer
41
            var json = buf.readString();
42
43
            // Unpack json
44
            var stats = new Gson().fromJson(json, GameStats.class);
45
46
            // Get the winner team id
47
            var winnerTeamId = gameManager.getGameModeManager().getGameMode().getWinnerTeamId();
48
49
            // If something went wrong
50
            if (winnerTeamId == -1) {
51
                LasertagMod.LOGGER.warn("Something went wrong while deciding what team won.");
52
            }
53
54
            // Set the winner team id
55
            uiState.lastGameWinnerId = winnerTeamId;
56
57
            var gameOverOverlayTimer = ThreadUtil.createScheduledExecutor("client-lasertag-game-over-timer-%d");
58
            gameOverOverlayTimer.schedule(() -> {
59
                uiState.lastGameWinnerId = -1;
60
                gameOverOverlayTimer.shutdownNow();
61
            }, 5, TimeUnit.SECONDS);
62
63
            // Get the winning team
64
            var winningTeam = teamsConfigState.getTeamOfId(winnerTeamId).orElseThrow();
65
66
            // Get the winning team text
67
            var winningTeamText = Text.literal(winningTeam.name()).setStyle(Style.EMPTY.withColor(winningTeam.color().getValue()));
68
69
            // Build the announcement message
70
            var message = Text.translatable("chat.message.winner_announcement", winningTeamText);
71
72
            // Send winning message in chat
73
            client.player.sendMessage(message);
74
75
            // If should generate file
76
            if (settingManager.<Boolean>get(SettingDescription.GEN_STATS_FILE)) {
77
78
                // Get the current game mode
79
                var gameMode = gameModeManager.getGameMode();
80
81
                // Generate file
82
                var generatedFilePath = WebStatisticsVisualizer.build(stats, winningTeam, gameMode, ResourceManagers.WEB_RESOURCE_MANAGER);
83
84
                // If generation failed
85
                if (generatedFilePath == null) {
86
87
                    LasertagMod.LOGGER.error("Failed to generate statistics file.");
88
                    client.player.sendMessage(Text.translatable("chat.message.game_stats_generate_failed")
89
                            .fillStyle(Style.EMPTY.withColor(Formatting.RED)), false);
90
91
                    return;
92
                }
93
94
                // Set the stats file
95
                client.setStatsFilePath(generatedFilePath.toString());
96
97
                // If should automatically open file
98
                if (settingManager.<Boolean>get(SettingDescription.AUTO_OPEN_STATS_FILE)) {
99
100
                    try {
101
                        DesktopApi.open(generatedFilePath.toFile());
102
                    } catch (Exception e) {
103
104
                        // Log error
105
                        LasertagMod.LOGGER.error("Failed to open statistics from '" + generatedFilePath + "': " + e.getMessage());
106
107
                        // Notify player
108
                        client.player.sendMessage(
109
                                Text.translatable("chat.message.game_stats_open_failed",
110
                                                generatedFilePath.toString())
111
                                        .fillStyle(Style.EMPTY.withColor(Formatting.RED)), false);
112
                    }
113
114
                } else {
115
116
                    // Notify player about generation of file
117
                    client.player.sendMessage(Text.translatable("chat.message.game_stats_saved"), false);
118
                }
119
            }
120
        } catch (Exception ex) {
121
            LasertagMod.LOGGER.error("Error in GameStatisticsIncomingCallback", ex);
122
            throw ex;
123
        }
124
    }
125
}
126