using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using Newtonsoft.Json; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UIElements; using SpaceRace.Shared; public class PlayerData { public Guid Id; } public class LapService { static string playerDataPath = Path.Combine(Application.persistentDataPath, "playerData.json"); string _mapName; PlayerData _player; PbDTO _pb; PbDTO _lr; public Lap Pb; public Lap LapRecord; public string Position => _pb switch { PbDTO pb => pb.Position.ToString(), null => "-", }; public string Completions => _lr switch { PbDTO lr => lr.Completions.ToString(), null => "-", }; public LapService(string mapName) { _mapName = mapName; LoadPlayerData(); } public IEnumerator GetLapTimes() { string uri = $"localhost:40080/LapTimes?userId={_player.Id}&mapName={_mapName}"; using (UnityWebRequest req = UnityWebRequest.Get(uri)) { yield return req.SendWebRequest(); switch (req.result) { case UnityWebRequest.Result.Success: Debug.Log("Received: " + req.downloadHandler.text); SetLapTimes(req.downloadHandler.text); break; default: Debug.LogError("Error: " + req.error); break; } } } void SetLapTimes(string json) { try { LapTimesDTO dto = JsonConvert.DeserializeObject(json); _pb = dto.Pb; _lr = dto.LapRecord; if (dto.Pb != null) Pb = new Lap { Map = _pb.Map, Sectors = _pb.Sectors.Select((d, i) => new SectorTime { Sector = i + 1, Seconds = d }).ToList(), }; if (dto.LapRecord != null) LapRecord = new Lap { Map = _lr.Map, Sectors = _lr.Sectors.Select((d, i) => new SectorTime { Sector = i + 1, Seconds = d }).ToList(), }; } catch (Exception e) { Debug.LogWarning($"Failed to set lap times {e}"); _pb = null; _lr = null; Pb = null; } } public IEnumerator PostLap(Lap lap) { LapDTO dto = new LapDTO { Id = Guid.NewGuid(), UserId = _player.Id, Map = _mapName, Time = lap.TotalTime, Sectors = lap.Sectors.Select(s => s.Seconds).ToList(), Created = DateTimeOffset.UtcNow, }; Debug.Log($"Posting lap: {JsonConvert.SerializeObject(dto)}"); using (UnityWebRequest req = UnityWebRequest.Post("localhost:40080/Lap", JsonConvert.SerializeObject(dto), "application/json")) { yield return req.SendWebRequest(); if (req.result != UnityWebRequest.Result.Success) { Debug.Log(req.error); } else { Debug.Log($"posted lap {dto}"); Debug.Log("Received: " + req.downloadHandler.text); SetLapTimes(req.downloadHandler.text); } } } void LoadPlayerData() { try { string json = File.ReadAllText(playerDataPath); _player = JsonConvert.DeserializeObject(json); Debug.Log($"Loaded player data {json}"); } catch { Debug.Log("No existing playerData.json"); CreatePlayerData(); } } PlayerData CreatePlayerData() { _player = new PlayerData { Id = Guid.NewGuid() }; Debug.Log(JsonConvert.SerializeObject(_player)); File.WriteAllText(playerDataPath, JsonConvert.SerializeObject(_player)); return _player; } }