2024-06-10 02:44:06 +04:00

200 lines
7.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Catamaran.Drawings;
using Catamaran.Exceptions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Catamaran.CollectionGenericObjects
{
public class StorageCollection<T>
where T : DrawingBoat
{
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
public List<CollectionInfo> Keys => _storages.Keys.ToList();
private readonly string _collectionKey = "CollectionsStorage";
private readonly string _separatorKeyValue = "|";
private readonly string _separatorItems = ";";
public StorageCollection()
{
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
public void AddCollection(string name, CollectionType collectionType)
{
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Array:
_storages[collectionInfo] = new ArrayGenericObjects<T>();
return;
case CollectionType.List:
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
}
}
public void DelCollection(string name)
{
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
_storages.Remove(collectionInfo);
}
}
public ICollectionGenericObjects<T>? this[string name]
{
get
{
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (!_storages.ContainsKey(collectionInfo))
{
return null;
}
return _storages[collectionInfo];
}
}
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
writer.Write(value.Key);
writer.Write(_separatorKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
writer.Write(data);
writer.Write(_separatorItems);
}
}
writer.Close();
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не существует!");
}
using (StreamReader reader = new(filename))
{
string line = reader.ReadLine();
if (line == null || line.Length == 0)
{
throw new ArgumentException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new InvalidDataException("В файле неверные данные");
}
_storages.Clear();
while ((line = reader.ReadLine()) != null)
{
string[] record = line.Split(_separatorKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 3)
{
continue;
}
//CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию о коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ?? throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new InvalidCastException("Не удалось определить тип коллекции: " + record[1]);
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingBoat() is T boat)
{
try
{
if (collection.Insert(boat) < 0)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
}
}
}
_storages.Add(collectionInfo, collection);
}
}
}
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Array => new ArrayGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}
}