using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sailboat { internal class MapsCollection { readonly Dictionary> _mapStorages; public List Keys => _mapStorages.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; private readonly char separatorDict = '|'; private readonly char separatorData = ';'; public MapsCollection(int pictureWidth, int pictureHeight) { _mapStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } public void AddMap(string name, AbstractMap map) { if (Keys.Contains(name)) return; _mapStorages.Add(name, new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); } public void DelMap(string name) { _mapStorages.Remove(name); } public MapWithSetBoatsGeneric this[string ind] { get { _mapStorages.TryGetValue(ind, out var result); return result; } } /// /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла /// public void SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } using (StreamWriter sw = new(filename)) { sw.Write($"MapsCollection{Environment.NewLine}"); foreach (var storage in _mapStorages) { sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } } /// /// Загрузка нформации по автомобилям на парковках из файла /// /// /// public void LoadData(string filename) { if (!File.Exists(filename)) { throw new FileNotFoundException("Файл не найден"); } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { throw new FileFormatException("Формат данных в файле не правильный"); } _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) { var tempElem = str.Split(separatorDict); AbstractMap map = null; switch (tempElem[1]) { case "SimpleMap": map = new SimpleMap(); break; case "WaterMap": map = new WaterMap(); break; } _mapStorages.Add(tempElem[0], new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } } } }