using System; using System.IO; using System.Text.Json; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; namespace TelegramBotBase.States; /// /// Is used for all complex data types. Use if other default machines are not working. /// public class JsonStateMachine : IStateMachine { /// /// Will initialize the state machine. /// /// Path of the file and name where to save the session details. /// /// Type of Form which will be saved instead of Form which has /// attribute declared. Needs to be subclass of /// . /// /// Declares of the file could be overwritten. public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { FallbackStateForm = fallbackStateForm; if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException($"{nameof(FallbackStateForm)} is not a subclass of {nameof(FormBase)}"); } FilePath = file ?? throw new ArgumentNullException(nameof(file)); Overwrite = overwrite; } public string FilePath { get; set; } public bool Overwrite { get; set; } public Type FallbackStateForm { get; } public StateContainer LoadFormStates() { try { var content = File.ReadAllText(FilePath); var sc = JsonSerializer.Deserialize(content); return sc; } catch { } return new StateContainer(); } public void SaveFormStates(SaveStatesEventArgs e) { if (File.Exists(FilePath)) { if (!Overwrite) { throw new Exception("File exists already."); } File.Delete(FilePath); } try { var content = JsonSerializer.Serialize(e.States, new JsonSerializerOptions { WriteIndented = true, }); File.WriteAllText(FilePath, content); } catch { } } }