using System.Text; namespace ElectricLocomotive; public class LocosGenericStorage { readonly Dictionary> _electricLocoStorages; public List Keys => _electricLocoStorages.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; private static readonly char _separatorForKeyValue = '|'; private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; public LocosGenericStorage(int pictureWidth, int pictureHeight) { _electricLocoStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } public void AddSet(string name) { _electricLocoStorages.Add(name, new LocosGenericCollection (_pictureWidth, _pictureHeight)); } public void DelSet(string name) { if (!_electricLocoStorages.ContainsKey(name)) return; _electricLocoStorages.Remove(name); } public LocosGenericCollection? this[string ind] { get { if (_electricLocoStorages.ContainsKey(ind)) return _electricLocoStorages[ind]; return null; } } public bool SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); foreach (KeyValuePair> record in _electricLocoStorages) { StringBuilder records = new(); foreach (DrawingLocomotiv? elem in record.Value.GetLocos) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { return false; } string toWrite = $"LocoStorage{Environment.NewLine}{data}"; var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); using (StreamWriter sw = new(filename)) { foreach (var str in strs) { sw.WriteLine(str); } } return true; } public bool LoadData(string filename) { if (!File.Exists(filename)) { return false; } using (StreamReader sr = new(filename)) { string str = sr.ReadLine(); var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); if (strs == null || strs.Length == 0) { return false; } if (!strs[0].StartsWith("LocoStorage")) { return false; } _electricLocoStorages.Clear(); do { string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { str = sr.ReadLine(); continue; } LocosGenericCollection collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { DrawingLocomotiv? monorail = elem?.CreateDrawingLoco(_separatorForObject, _pictureWidth, _pictureHeight); if (monorail != null) { if (!(collection + monorail)) { return false; } } } _electricLocoStorages.Add(record[0], collection); str = sr.ReadLine(); } while (str != null); } return true; } }