using Lab.DrawningObjects; using Lab.MovementStrategy; using Lab.Generics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab.Generics { internal class CarsGenericStorage { readonly Dictionary> _carStorages; public List Keys => _carStorages.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; private static readonly char _separatorForKeyValue = '|'; private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; public CarsGenericStorage(int pictureWidth, int pictureHeight) { _carStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } public void AddSet(string name) { if (_carStorages.ContainsKey(name)) return; _carStorages[name] = new CarsGenericCollection(_pictureWidth, _pictureHeight); } public void DelSet(string name) { if (!_carStorages.ContainsKey(name)) return; _carStorages.Remove(name); } public CarsGenericCollection? this[string ind] { get { if (_carStorages.ContainsKey(ind)) return _carStorages[ind]; return null; } } public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); foreach (KeyValuePair> record in _carStorages) { StringBuilder records = new(); foreach (DrawTanker? elem in record.Value.GetCars) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { throw new Exception("Невалидная операция, нет данных для сохранения"); } using (StreamWriter writer = new StreamWriter(filename)) { writer.WriteLine("CarStorage"); writer.Write(data.ToString()); } } public void LoadData(string filename) { if (!File.Exists(filename)) { throw new Exception("Файл не найден"); } using (StreamReader reader = new StreamReader(filename)) { string checker = reader.ReadLine(); if (checker == null) throw new Exception("Нет данных для загрузки"); if (!checker.StartsWith("CarStorage")) throw new Exception("Неверный формат ввода"); _carStorages.Clear(); string strs; bool firstinit = true; while ((strs = reader.ReadLine()) != null) { if (strs == null && firstinit) throw new Exception("Нет данных для загрузки"); if (strs == null ) break; firstinit = false; string name = strs.Split('|')[0]; CarsGenericCollection collection = new(_pictureWidth, _pictureHeight); foreach (string data in strs.Split('|')[1].Split(';')) { DrawTanker? car = data?.CreateDrawTanker(_separatorForObject, _pictureWidth, _pictureHeight); if (car != null) { try {_ = collection + car; } catch (CarNotFoundException e) { throw e; } catch (StorageOverflowException e) { throw e; } } } _carStorages.Add(name, collection); } } } } }