194 lines
8.0 KiB
C#
194 lines
8.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using RoadTrain.DrawningObjects;
|
|
using RoadTrain.MovementStrategy;
|
|
using RoadTrain.Exceptions;
|
|
|
|
|
|
namespace RoadTrain.Generics
|
|
{
|
|
/// <summary>
|
|
/// Класс для хранения коллекции
|
|
/// </summary>
|
|
internal class RoadTrainGenericStorage
|
|
{
|
|
/// <summary>
|
|
/// Словарь (хранилище)
|
|
/// </summary>
|
|
readonly Dictionary<TrainsCollectionInfo, RoadTrainGenericCollection<DrawningRoadTrain,
|
|
DrawningObjectTrain>> _trainStorages;
|
|
/// <summary>
|
|
/// Возвращение списка названий наборов
|
|
/// </summary>
|
|
public List<TrainsCollectionInfo> Keys => _trainStorages.Keys.ToList();
|
|
/// <summary>
|
|
/// Ширина окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureWidth;
|
|
/// <summary>
|
|
/// Высота окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureHeight;
|
|
/// <summary>
|
|
/// Разделитель для записи ключа и значения элемента словаря
|
|
/// </summary>
|
|
private static readonly char _separatorForKeyValue = '|';
|
|
/// <summary>
|
|
/// Разделитель для записей коллекции данных в файл
|
|
/// </summary>
|
|
private readonly char _separatorRecords = ';';
|
|
/// <summary>
|
|
/// Разделитель для записи информации по объекту в файл
|
|
/// </summary>
|
|
private static readonly char _separatorForObject = ':';
|
|
|
|
/// <summary>
|
|
/// Конструктор
|
|
/// </summary>
|
|
/// <param name="pictureWidth"></param>
|
|
/// <param name="pictureHeight"></param>
|
|
public RoadTrainGenericStorage(int pictureWidth, int pictureHeight)
|
|
{
|
|
_trainStorages = new Dictionary<TrainsCollectionInfo,
|
|
RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain>>();
|
|
_pictureWidth = pictureWidth;
|
|
_pictureHeight = pictureHeight;
|
|
}
|
|
/// <summary>
|
|
/// Добавление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void AddSet(string name)
|
|
{
|
|
if (_trainStorages.ContainsKey(new TrainsCollectionInfo(name, string.Empty))) return;
|
|
_trainStorages.Add(new TrainsCollectionInfo(name, string.Empty), new RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain>(_pictureWidth, _pictureHeight));
|
|
}
|
|
/// <summary>
|
|
/// Удаление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void DelSet(string name)
|
|
{
|
|
if (_trainStorages.ContainsKey(new TrainsCollectionInfo(name, string.Empty))) _trainStorages.Remove(new TrainsCollectionInfo(name, string.Empty));
|
|
return;
|
|
}
|
|
/// <summary>
|
|
/// Доступ к набору
|
|
/// </summary>
|
|
/// <param name="ind"></param>
|
|
/// <returns></returns>
|
|
public RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain>?
|
|
this[string ind]
|
|
{
|
|
get
|
|
{
|
|
TrainsCollectionInfo indObj = new TrainsCollectionInfo(ind, string.Empty);
|
|
if (_trainStorages.ContainsKey(indObj))
|
|
return _trainStorages[indObj];
|
|
return null;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Сохранение информации по автомобилям в хранилище в файл
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
|
public void SaveData(string filename)
|
|
{
|
|
if (File.Exists(filename))
|
|
{
|
|
File.Delete(filename);
|
|
}
|
|
StringBuilder data = new();
|
|
foreach (KeyValuePair<TrainsCollectionInfo,
|
|
RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain>> record in _trainStorages)
|
|
{
|
|
StringBuilder records = new();
|
|
foreach (DrawningRoadTrain? elem in record.Value.GetTrains)
|
|
{
|
|
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
|
}
|
|
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
|
}
|
|
if (data.Length == 0)
|
|
{
|
|
throw new ArgumentException("Невалидная операция, нет данных для сохранения");
|
|
}
|
|
string dataStr = data.ToString();
|
|
using (StreamWriter writer = new StreamWriter(filename))
|
|
{
|
|
writer.WriteLine("TrainStorage");
|
|
writer.WriteLine(dataStr);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Загрузка информации по автомобилям в хранилище из файла
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
|
public void LoadData(string filename)
|
|
{
|
|
if (!File.Exists(filename))
|
|
{
|
|
throw new FileNotFoundException("Файл не найден");
|
|
}
|
|
using (StreamReader reader = new StreamReader(filename))
|
|
{
|
|
string checker = reader.ReadLine();
|
|
if (checker == null)
|
|
{
|
|
throw new ArgumentException("Нет данных для загрузки");
|
|
}
|
|
if (!checker.StartsWith("TrainStorage"))
|
|
{
|
|
throw new InvalidDataException("Неверный формат данных");
|
|
}
|
|
_trainStorages.Clear();
|
|
string strs;
|
|
bool firstinit = true;
|
|
while ((strs = reader.ReadLine()) != null)
|
|
{
|
|
if (strs == null && firstinit)
|
|
throw new ArgumentException("Нет данных для загрузки");
|
|
if (strs == null)
|
|
break;
|
|
if (strs == String.Empty)
|
|
break;
|
|
firstinit = false;
|
|
string name = strs.Split('|')[0];
|
|
RoadTrainGenericCollection<DrawningRoadTrain, DrawningObjectTrain> collection = new(_pictureWidth, _pictureHeight);
|
|
foreach (string data in strs.Split('|')[1].Split(';').Reverse())
|
|
{
|
|
DrawningRoadTrain? train =
|
|
data?.CreateDrawningTrain(_separatorForObject, _pictureWidth, _pictureHeight);
|
|
if (train != null)
|
|
{
|
|
if (collection + train == -1)
|
|
{
|
|
try
|
|
{
|
|
_ = collection + train;
|
|
}
|
|
catch (TrainNotFoundException e)
|
|
{
|
|
throw e;
|
|
}
|
|
catch (StorageOverflowException e)
|
|
{
|
|
throw e;
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
_trainStorages.Add(new TrainsCollectionInfo(name, string.Empty), collection);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|