PIbd-22_Kurbanova_A.A.Warml.../WarmlyLocomotive/WarmlyLocomotivesGenericStorage.cs
2023-12-23 13:58:32 +04:00

145 lines
6.3 KiB
C#

using System.Text;
using WarmlyLocomotive.DrawningObjects;
using WarmlyLocomotive.MovementStrategy;
namespace WarmlyLocomotive.Generics
{
internal class WarmlyLocomotivesGenericStorage
{
readonly Dictionary<string, WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> _warmlylocomotiveStorages;
public List<string> Keys => _warmlylocomotiveStorages.Keys.ToList();
private readonly int _pictureWidth;
private readonly int _pictureHeight;
public WarmlyLocomotivesGenericStorage(int pictureWidth, int pictureHeight)
{
_warmlylocomotiveStorages = new Dictionary<string,
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void AddSet(string name)
{
_warmlylocomotiveStorages.Add(name, new WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>(_pictureWidth, _pictureHeight));
}
public void DelSet(string name)
{
if (!_warmlylocomotiveStorages.ContainsKey(name))
return;
_warmlylocomotiveStorages.Remove(name);
}
public WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>? this[string ind]
{
get
{
if (_warmlylocomotiveStorages.ContainsKey(ind))
return _warmlylocomotiveStorages[ind];
return null;
}
}
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private static readonly char _separatorForKeyValue = '|';
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly char _separatorRecords = ';';
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly char _separatorForObject = ':';
/// <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<string,
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>> record in _warmlylocomotiveStorages)
{
StringBuilder records = new();
foreach (DrawningWarmlyLocomotive? elem in record.Value.GetWarmlyLocomotives)
{
records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}");
}
data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}");
}
if (data.Length == 0)
{
return false;
}
using FileStream fs = new(filename, FileMode.Create);
byte[] info = new
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
fs.Write(info, 0, info.Length);
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0)
{
return false;
}
if (!strs[0].StartsWith("CarStorage"))
{
//если нет такой записи, то это не те данные
return false;
}
_warmlylocomotiveStorages.Clear();
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
}
WarmlyLocomotivesGenericCollection<DrawningWarmlyLocomotive, DrawningObjectWarmlyLocomotive>
collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords,
StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
DrawningWarmlyLocomotive? warmlylocomotive=
elem?.CreateDrawningWarmlyLocomotive(_separatorForObject, _pictureWidth, _pictureHeight);
if (warmlylocomotive != null)
{
if (!(collection + warmlylocomotive))
{
return false;
}
}
}
_warmlylocomotiveStorages.Add(record[0], collection);
}
return true;
}
}
}