PixelPlacerBot/app/Http/Controllers/TwitchController.php
2024-07-27 15:40:35 -04:00

101 lines
3.4 KiB
PHP
Executable File

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\TwitchHelper;
use App\Models\TwitchUser;
use App\Models\CommandHistory;
use App\Models\CurrentState;
use App\Models\GameSession;
use Illuminate\Support\Facades\Log;
class TwitchController extends Controller
{
public function parseChatMessage(Request $request)
{
Log::info("Entered parseChatMessage");
$message = $request->input('message');
$username = $request->input('username');
$gameSession = $this->getCurrentGameSession();
Log::debug('TwitchController::parseChatMessage', [
'message' => $message,
'username' => $username,
'gameSessionId' => $gameSession->id
]);
if (!$message || !$username || !$gameSession) {
Log::debug('TwitchController::parseChatMessage - Missing input or invalid game session', [
'message' => $message,
'username' => $username,
'gameSession' => $gameSession
]);
return response()->json(['error' => 'No message, username, or valid game session provided'], 400);
}
$user = TwitchUser::firstOrCreate(['twitch_username' => $username]);
$parsedCommand = TwitchHelper::parseMessage($message);
Log::debug('TwitchController::parseChatMessage - Parsed Command', ['parsedCommand' => $parsedCommand]);
if ($parsedCommand) {
CommandHistory::create([
'user_id' => $user->id,
'command' => $parsedCommand['command'],
'x' => $parsedCommand['x'] ?? null,
'y' => $parsedCommand['y'] ?? null,
'color' => $parsedCommand['color'] ?? null,
'game_session_id' => $gameSession->id,
]);
switch ($parsedCommand['command']) {
case 'place':
$this->handlePlaceCommand($parsedCommand, $user->id);
break;
// Add cases for other commands like 'row', 'column', 'fill'
}
return response()->json($parsedCommand);
}
Log::debug('TwitchController::parseChatMessage - Invalid command', ['message' => $message]);
return response()->json(['error' => 'Invalid command'], 400);
}
private function handlePlaceCommand($parsedCommand, $userId)
{
Log::debug('TwitchController::handlePlaceCommand', ['command' => $parsedCommand]);
$x = $parsedCommand['x'];
$y = $parsedCommand['y'];
$color = $parsedCommand['color'];
$currentState = CurrentState::where('x', $x)->where('y', $y)->first();
Log::debug('TwitchController::handlePlaceCommand - Retrieved Current State', ['currentState' => $currentState]);
if ($currentState) {
$currentState->update(['color' => $color, 'updated_by' => $userId]);
} else {
CurrentState::create(['x' => $x, 'y' => $y, 'color' => $color, 'updated_by' => $userId]);
}
}
private function getCurrentGameSession()
{
$gameSession = GameSession::whereNull('ended_at')->latest()->first();
if (!$gameSession) {
$gameSession = GameSession::create(['session_name' => 'Session ' . now()]);
}
return $gameSession;
}
public function getCurrentState()
{
$currentState = CurrentState::all();
return response()->json($currentState);
}
}