using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WinFormsApp1 { 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 (_mapStorages.ContainsKey(name)) return; //уникальное имя else { _mapStorages.Add(name, new MapWithSetTraktorGeneric(_pictureWidth, _pictureHeight, map)); } } public void DelMap(string name) { if (_mapStorages.ContainsKey(name)) { _mapStorages.Remove(name); } } public MapWithSetTraktorGeneric this[string ind] { get { _mapStorages.TryGetValue(ind, out var result); return result; } } private static void WriteToFile(string text, FileStream stream) { byte[] info = new UTF8Encoding(true).GetBytes(text); stream.Write(info, 0, info.Length); } public bool SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } using (StreamWriter fs = new(filename)) { fs.Write($"MapsCollection{Environment.NewLine}"); foreach (var storage in _mapStorages) { fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); } } return true; } public bool LoadData(string filename) { if (!File.Exists(filename)) { return false; } using (StreamReader sr = new(filename)) { string str = ""; if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) { //если нет такой записи, то это не те данные return false; } //очищаем записи _mapStorages.Clear(); while ((str = sr.ReadLine()) != null) { var elem = str.Split(separatorDict); AbstractMap map = null; switch (elem[1]) { case "Простая карта": map = new SimpleMap(); break; case "Поле": map = new FieldMap(); break; } _mapStorages.Add(elem[0], new MapWithSetTraktorGeneric(_pictureWidth, _pictureHeight, map)); _mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); } } return true; } } }