using AirBomber.MovementStrategy; using AirBomber.Rendering; using System.Text; namespace AirBomber.Generics { internal class EntitiesGenericStorage { readonly Dictionary> _entityStorages; public List Keys => _entityStorages.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; private readonly char _keyValueDelimiter = '|'; private readonly char _recordsDelimiter = ';'; private readonly char _entityDelimiter = ':'; public EntitiesGenericStorage(int PictureWidth, int PictureHeight) { _entityStorages = new Dictionary>(); _pictureWidth = PictureWidth; _pictureHeight = PictureHeight; } public void AddSet(string Name) { var NewCollection = new EntitiesGenericCollection(_pictureWidth, _pictureHeight); if (Keys.Contains(Name)) { MessageBox.Show("Набор с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _entityStorages.Add(Name, NewCollection); } public void RemoveSet(string Name) { _entityStorages.Remove(Name); } public EntitiesGenericCollection? this[string Index] { get { if (!_entityStorages.ContainsKey(Index)) return null; return _entityStorages[Index]; } } public bool SaveData(string FileName) { if (_entityStorages.Count == 0) return false; using (StreamWriter writer = new StreamWriter(FileName, false)) { writer.WriteLine("BomberStorage"); foreach (KeyValuePair> Record in _entityStorages) { StringBuilder Records = new StringBuilder(); foreach (BomberRendererBase? Element in Record.Value.Entities) Records.Append($"{Element?.SerializeRenderer(_entityDelimiter)}{_recordsDelimiter}"); writer.WriteLine($"{Record.Key}{_keyValueDelimiter}{Records}"); } } return true; } public bool LoadData(string FileName) { if (!File.Exists(FileName)) return false; using (StreamReader reader = new StreamReader(FileName)) { if (reader.ReadLine() != "BomberStorage") return false; _entityStorages.Clear(); string? Data; while ((Data = reader.ReadLine()) != null) { string[] Record = Data.Split(_keyValueDelimiter, StringSplitOptions.RemoveEmptyEntries); if (Record.Length != 2) continue; EntitiesGenericCollection Collection = new(_pictureWidth, _pictureHeight); string[] Set = Record[1].Split(_recordsDelimiter, StringSplitOptions.RemoveEmptyEntries); foreach (string Element in Set) { BomberRendererBase? Renderer = Element?.DeserializeRenderer(_entityDelimiter, _pictureWidth, _pictureHeight); if (Renderer != null) { if ((Collection + Renderer) == -1) return false; } } _entityStorages.Add(Record[0], Collection); } } return true; } } }