using AirBomber.Drawnings; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AirBomber.CollectionGenericObjects; /// /// Класс-хранилище коллекций /// /// public class StorageCollection where T : DrawningAirPlane { /// /// Словарь (хранилище) с коллекциями /// readonly Dictionary> _storages; /// /// Возвращение списка названий коллекций /// public List Keys => _storages.Keys.ToList(); /// /// Ключевое слово, с которого должен начинаться файл /// private readonly string _collectionKey = "CollectionsStorage"; /// /// Разделитель для записи ключа и значения элемента словаря /// private readonly string _separatorForKeyValue = "|"; /// /// Разделитель для записей коллекции данных в файл /// private readonly string _separatorItems = ";"; /// /// Конструктор /// public StorageCollection() { _storages = new Dictionary>(); } /// /// Добавление коллекции в хранилище /// /// Название коллекции /// тип коллекции public void AddCollection(string name, CollectionType collectionType) { if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name)) { return; } switch (collectionType) { case CollectionType.Massive: _storages[name] = new MassiveGenericObjects(); break; case CollectionType.List: _storages[name] = new ListGenericObjects(); break; default: return; } } /// /// Удаление коллекции /// /// Название коллекции public void DelCollection(string name) { if (_storages.ContainsKey(name)) { _storages.Remove(name); } } /// /// Доступ к коллекции /// /// Название коллекции /// public ICollectionGenericObjects? this[string name] { get { if (_storages.ContainsKey(name)) { return _storages[name]; } return null; } } /// /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла /// true - сохранение прошло успешно, false - ошибка при сохранении данных public bool SaveData(string filename) { if (_storages.Count == 0) { return false; } if (File.Exists(filename)) { File.Delete(filename); } StringBuilder sb = new(); using (StreamWriter sw = new StreamWriter(filename)) { sw.WriteLine(_collectionKey.ToString()); foreach (KeyValuePair> kvpair in _storages) { // не сохраняем пустые коллекции if (kvpair.Value.Count == 0) continue; sb.Append(kvpair.Key); sb.Append(_separatorForKeyValue); sb.Append(kvpair.Value.GetCollectionType); sb.Append(_separatorForKeyValue); sb.Append(kvpair.Value.MaxCount); sb.Append(_separatorForKeyValue); foreach (T? item in kvpair.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; if (string.IsNullOrEmpty(data)) continue; sb.Append(data); sb.Append(_separatorItems); } sw.WriteLine(sb.ToString()); sb.Clear(); } } return true; } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных public bool LoadData(string filename) { if (!File.Exists(filename)) { return false; } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); if (str != _collectionKey.ToString()) return false; _storages.Clear(); while ((str = sr.ReadLine()) != null) { string[] record = str.Split(_separatorForKeyValue); if (record.Length != 4) { continue; } CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { return false; } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { if (elem?.CreateDrawningAirPlane() is T boat) { if (collection.Insert(boat) == -1) return false; } } _storages.Add(record[0], collection); } } return true; } /// /// Создание коллекции по типу /// /// /// private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { return collectionType switch { CollectionType.Massive => new MassiveGenericObjects(), CollectionType.List => new ListGenericObjects(), _ => null, }; } }