This commit is contained in:
Anastasia Yazykova 2024-06-11 04:56:10 +04:00
commit da6a8237a8

View File

@ -1,5 +1,4 @@
using ProjectTrolleybus.Exceptions; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -16,12 +15,12 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages; readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<CollectionInfo> Keys => _storages.Keys.ToList(); public List<string> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Ключевое слово, с которого должен начинаться файл /// Ключевое слово, с которого должен начинаться файл
@ -43,7 +42,7 @@ public class StorageCollection<T>
/// ///
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>(); _storages = new Dictionary<string, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -52,36 +51,29 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
CollectionInfo collectionInfo = new(name, collectionType, string.Empty); if (_storages.ContainsKey(name) && name == "")
if (name == null || _storages.ContainsKey(collectionInfo))
return;
switch (collectionType)
{ {
case CollectionType.None:
return; return;
case CollectionType.Massive:
_storages[collectionInfo] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
default:
break;
} }
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
} }
else
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
/// </summary> /// </summary>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); _storages.Remove(name);
if (_storages.ContainsKey(collectionInfo)) }
{
_storages.Remove(collectionInfo);
}
}
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
/// </summary> /// </summary>
@ -91,13 +83,12 @@ public class StorageCollection<T>
{ {
get get
{ {
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty); if (name == "")
if (_storages.ContainsKey(collectionInfo))
{ {
return _storages[collectionInfo];
}
return null; return null;
} }
return _storages[name];
}
} }
public void SaveData(string filename) public void SaveData(string filename)
@ -111,13 +102,10 @@ public class StorageCollection<T>
{ {
File.Delete(filename); File.Delete(filename);
} }
using (StreamWriter writer = new(filename)) using (StreamWriter writer = new(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{ {
writer.Write(Environment.NewLine); writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции // не сохраняем пустые коллекции
@ -153,38 +141,38 @@ public class StorageCollection<T>
{ {
throw new FileNotFoundException("Файл не существует!"); throw new FileNotFoundException("Файл не существует!");
} }
using (StreamReader reader = new(filename))
using (StreamReader sr = new(filename))
{ {
string? line = sr.ReadLine(); string line = reader.ReadLine();
if (line == null || line.Length == 0) if (line == null || line.Length == 0)
{ {
throw new ArgumentException("В файле нет данных"); throw new ArgumentException("В файле нет данных");
} }
if (!line.Equals(_collectionKey))
if (line != _collectionKey)
{ {
throw new InvalidDataException("В файле неверные данные"); throw new InvalidDataException("В файле неверные данные");
} }
_storages.Clear(); _storages.Clear();
while ((line = reader.ReadLine()) != null)
while ((line = sr.ReadLine()) != null)
{ {
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = line.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3) if (record.Length != 4)
{ {
continue; continue;
} }
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ?? throw new ArgumentNullException("Не удалось определить тип коллекции: " + record[0]); CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new ArgumentNullException("Не удалось создать коллекцию"); ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
collection.MaxCount = Convert.ToInt32(record[1]); if (collection == null)
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); {
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningBus() is T bus) if (elem?.CreateDrawningBus() is T bus )
{ {
try try
{ {
@ -201,9 +189,10 @@ public class StorageCollection<T>
} }
} }
_storages.Add(collectionInfo, collection); _storages.Add(record[0], collection);
} }
} }
} }
/// <summary> /// <summary>
@ -211,7 +200,8 @@ public class StorageCollection<T>
/// </summary> /// </summary>
/// <param name="collectionType"></param> /// <param name="collectionType"></param>
/// <returns></returns> /// <returns></returns>
private static ICollectionGenericObjects<T>?CreateCollection(CollectionType collectionType) private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{ {
return collectionType switch return collectionType switch
{ {