using ProjectBulldozer.Drawing; using ProjectBulldozer.Drawning; using System.Text; namespace ProjectBulldozer.Generics { internal class TractorGenericStorage { private static readonly char _separatorForKeyValue = '|'; private readonly char _separatorRecords = ';'; private static readonly char _separatorForObject = ':'; readonly Dictionary> _TractorsStorage; public List Keys => _TractorsStorage.Keys.ToList(); private readonly int _pictureWidth; private readonly int _pictureHeight; public TractorGenericStorage(int pictureWidth, int pictureHeight) { _TractorsStorage = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } public void AddSet(string name) { if (!_TractorsStorage.ContainsKey(name)) { _TractorsStorage.Add(name, new TractorGenericCollection(_pictureWidth, _pictureHeight)); } } public void DelSet(string name) { if (_TractorsStorage.ContainsKey(name)) { _TractorsStorage.Remove(name); } } public TractorGenericCollection? this[string ind] { get { if (_TractorsStorage.ContainsKey(ind)) { return _TractorsStorage[ind]; } return null; } } public bool SaveData(string filename) { if (File.Exists(filename)) { File.Delete(filename); } StringBuilder data = new(); foreach (KeyValuePair> record in _TractorsStorage) { StringBuilder records = new(); foreach (DrawingTractor? elem in record.Value.GetTractors) { records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); } data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); } if (data.Length == 0) { return false; } using StreamWriter sw = new(filename); sw.Write($"TractorsStorage{Environment.NewLine}{data}"); return true; } public bool LoadData(string filename) { if (!File.Exists(filename)) { return false; } using (StreamReader sr = File.OpenText(filename)) { string str = sr.ReadLine(); if (str == null || str.Length == 0) { return false; } if (!str.StartsWith("TractorsStorage")) { return false; } _TractorsStorage.Clear(); string strs = ""; while ((strs = sr.ReadLine()) != null) { if (strs == null) { return false; } string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 2) { continue; } TractorGenericCollection collection = new(_pictureWidth, _pictureHeight); string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { DrawingTractor? tractor = elem?.CreateDrawingTractor(_separatorForObject, _pictureWidth, _pictureHeight); if (tractor != null) { if ((collection + tractor) == -1) { return false; } } } _TractorsStorage.Add(record[0], collection); } return true; } } } }