using System; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; namespace Soundings { [Serializable] internal sealed class CareerSave { public int Version = 1; public string Id, Name; public long SavedUtc; public int Page, DeckIndex; public Company Company; public FleetPassageSnapshot[] Passages; } internal sealed class CareerStore { private readonly string directory; internal CareerStore(string directory) => this.directory = directory; internal string RecentId { get { string path = Path.Combine(directory, "recent"); try { return File.Exists(path) ? File.ReadAllText(path) : null; } catch (Exception error) when (IsFileError(error)) { return null; } } } internal List List() { var result = new List(); if (!Directory.Exists(directory)) return result; try { foreach (string file in Directory.GetFiles(directory, "*.json")) { CareerSave saved = Read(Path.GetFileNameWithoutExtension(file)); if (saved != null) result.Add(saved); } } catch (Exception error) when (IsFileError(error)) { Debug.LogWarning("Could not list careers. " + error.Message); } result.Sort((a, b) => b.SavedUtc.CompareTo(a.SavedUtc)); return result; } internal CareerSave Read(string id) { if (!Guid.TryParseExact(id, "N", out _)) return null; try { string path = Path.Combine(directory, id + ".json"); if (!File.Exists(path)) return null; CareerSave saved = JsonUtility.FromJson(File.ReadAllText(path)); return saved is { Version: 1, Company: not null } && saved.Id == id && !string.IsNullOrWhiteSpace(saved.Name) ? saved : null; } catch (Exception error) when (IsFileError(error) || error is ArgumentException) { Debug.LogWarning("Could not read a career. " + error.Message); return null; } } internal bool Write(CareerSave saved) { try { Directory.CreateDirectory(directory); ReplaceFile(Path.Combine(directory, saved.Id + ".json"), JsonUtility.ToJson(saved)); } catch (Exception error) when (IsFileError(error)) { Debug.LogWarning("Could not write a career. " + error.Message); return false; } Select(saved.Id); return true; } internal void Select(string id) { try { ReplaceFile(Path.Combine(directory, "recent"), id); } catch (Exception error) when (IsFileError(error)) { Debug.LogWarning("Could not set the most recent career. " + error.Message); } } private static void ReplaceFile(string path, string contents) { string temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (var file = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None)) { byte[] bytes = Encoding.UTF8.GetBytes(contents); file.Write(bytes, 0, bytes.Length); file.Flush(true); } if (File.Exists(path)) File.Replace(temporary, path, null); else File.Move(temporary, path); } finally { if (File.Exists(temporary)) File.Delete(temporary); } } private static bool IsFileError(Exception error) => error is IOException or UnauthorizedAccessException; } }