179 lines
7.6 KiB
C#
179 lines
7.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Cruiser.Drawing;
|
|
using Cruiser.MovementStrategy;
|
|
using System.IO;
|
|
|
|
namespace Cruiser.Generics
|
|
{
|
|
internal class CruisersGenericStorage
|
|
{
|
|
/// <summary>
|
|
/// Разделитель для записи ключа и значения элемента словаря
|
|
/// </summary>
|
|
private static readonly char _separatorForKeyValue = '|';
|
|
/// <summary>
|
|
/// Разделитель для записей коллекции данных в файл
|
|
/// </summary>
|
|
private readonly char _separatorRecords = ';';
|
|
/// <summary>
|
|
/// Разделитель для записи информации по объекту в файл
|
|
/// </summary>
|
|
private static readonly char _separatorForObject = ':';
|
|
|
|
/// <summary>
|
|
/// Словарь (хранилище)
|
|
/// </summary>
|
|
readonly Dictionary<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> _cruiserStorages;
|
|
/// <summary>
|
|
/// Возвращение списка названий наборов
|
|
/// </summary>
|
|
public List<CruiserCollectionInfo> Keys => _cruiserStorages.Keys.ToList();
|
|
/// <summary>
|
|
/// Ширина окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureWidth;
|
|
/// <summary>
|
|
/// Высота окна отрисовки
|
|
/// </summary>
|
|
private readonly int _pictureHeight;
|
|
/// <summary>
|
|
/// Конструктор
|
|
/// </summary>
|
|
/// <param name="pictureWidth"></param>
|
|
/// <param name="pictureHeight"></param>
|
|
public CruisersGenericStorage(int pictureWidth, int pictureHeight)
|
|
{
|
|
_cruiserStorages = new Dictionary<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>>();
|
|
_pictureWidth = pictureWidth;
|
|
_pictureHeight = pictureHeight;
|
|
}
|
|
/// <summary>
|
|
/// Добавление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void AddSet(string name)
|
|
{
|
|
if (_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty))) return;
|
|
_cruiserStorages[new CruiserCollectionInfo(name, string.Empty)] = new CarsGenericCollection<DrawingCruiser, DrawningObjectCar>(_pictureWidth, _pictureHeight);
|
|
}
|
|
/// <summary>
|
|
/// Удаление набора
|
|
/// </summary>
|
|
/// <param name="name">Название набора</param>
|
|
public void DelSet(string name)
|
|
{
|
|
if (!_cruiserStorages.ContainsKey(new CruiserCollectionInfo(name, string.Empty))) return;
|
|
_cruiserStorages.Remove(new CruiserCollectionInfo(name, string.Empty));
|
|
}
|
|
/// <summary>
|
|
/// Доступ к набору
|
|
/// </summary>
|
|
/// <param name="ind"></param>
|
|
/// <returns></returns>
|
|
public CarsGenericCollection<DrawingCruiser, DrawningObjectCar>?
|
|
this[string ind]
|
|
{
|
|
get
|
|
{
|
|
if (_cruiserStorages.ContainsKey(new CruiserCollectionInfo(ind, string.Empty))) return _cruiserStorages[new CruiserCollectionInfo(ind, string.Empty)];
|
|
return null;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Сохранение информации по автомобилям в хранилище в файл
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
|
|
public bool SaveData(string filename)
|
|
{
|
|
if (File.Exists(filename))
|
|
{
|
|
File.Delete(filename);
|
|
}
|
|
StringBuilder data = new();
|
|
foreach (KeyValuePair<CruiserCollectionInfo, CarsGenericCollection<DrawingCruiser, DrawningObjectCar>> record in _cruiserStorages)
|
|
{
|
|
StringBuilder records = new();
|
|
foreach (DrawingCruiser? elem in record.Value.GetCruisers)
|
|
{
|
|
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
|
|
}
|
|
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
|
|
}
|
|
if (data.Length == 0)
|
|
{
|
|
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
|
}
|
|
string dataStr = data.ToString();
|
|
using (StreamWriter writer = new StreamWriter(filename))
|
|
{
|
|
writer.WriteLine("CruiserStorage");
|
|
writer.WriteLine(dataStr);
|
|
}
|
|
return true;
|
|
}
|
|
/// <summary>
|
|
/// Загрузка информации по крейсеру в хранилище из файла
|
|
/// </summary>
|
|
/// <param name="filename">Путь и имя файла</param>
|
|
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
|
|
public bool 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 NullReferenceException("Нет данных для загрузки");
|
|
}
|
|
if (!checker.StartsWith("CruiserStorage"))
|
|
{
|
|
throw new FormatException("Неверный формат данных");
|
|
}
|
|
_cruiserStorages.Clear();
|
|
string strs;
|
|
bool firstinit = true;
|
|
while ((strs = reader.ReadLine()) != null)
|
|
{
|
|
if (strs == null && firstinit)
|
|
return false;
|
|
if (strs == null)
|
|
break;
|
|
if (strs == string.Empty)
|
|
break;
|
|
firstinit = false;
|
|
string name = strs.Split('|')[0];
|
|
CarsGenericCollection<DrawingCruiser, DrawningObjectCar> collection = new(_pictureWidth, _pictureHeight);
|
|
foreach (string data in strs.Split('|')[1].Split(';').Reverse())
|
|
{
|
|
DrawingCruiser? cruiser = data?.CreateDrawingCruiser(_separatorForObject, _pictureWidth, _pictureHeight);
|
|
if (cruiser != null)
|
|
{
|
|
try
|
|
{
|
|
bool? tmp = collection + cruiser;
|
|
}
|
|
catch (ApplicationException ex)
|
|
{
|
|
throw new ApplicationException($"Ошибка добавления в коллекцию: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
}
|
|
_cruiserStorages.Add(new CruiserCollectionInfo(name, string.Empty), collection);
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|