-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSessionManager.cs
More file actions
125 lines (110 loc) · 2.96 KB
/
SessionManager.cs
File metadata and controls
125 lines (110 loc) · 2.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace stack;
public static class SessionManager
{
private static readonly string SessionFilePath = Path.Combine(AppContext.BaseDirectory, "session.json");
private static readonly object _fileLock = new();
public static List<NoteData> Load()
{
lock (_fileLock)
{
if (!File.Exists(SessionFilePath))
return new List<NoteData>();
try
{
var json = File.ReadAllText(SessionFilePath);
return JsonSerializer.Deserialize(json, NoteDataJsonContext.Default.ListNoteData) ?? new List<NoteData>();
}
catch
{
return new List<NoteData>();
}
}
}
public static void Save(List<NoteData> notes)
{
lock (_fileLock)
{
try
{
var json = JsonSerializer.Serialize(notes, NoteDataJsonContext.Default.ListNoteData);
File.WriteAllText(SessionFilePath, json);
}
catch
{
}
}
}
public static void Push(NoteData note)
{
var notes = Load();
var existing = notes.FirstOrDefault(n => n.Id == note.Id);
note.IsStashed = true;
note.LastAccessed = DateTime.UtcNow;
if (existing != null)
{
notes[notes.IndexOf(existing)] = note;
}
else
{
notes.Add(note);
}
Save(notes);
}
public static NoteData? Pop()
{
var notes = Load();
var mostRecentStashed = notes
.Where(n => n.IsStashed)
.OrderByDescending(n => n.LastAccessed)
.FirstOrDefault();
if (mostRecentStashed != null)
{
mostRecentStashed.IsStashed = false;
mostRecentStashed.LastAccessed = DateTime.UtcNow;
Save(notes);
return mostRecentStashed;
}
return null; // Return null if stack is empty
}
public static NoteData? PopSpecific(Guid id)
{
var notes = Load();
var note = notes.FirstOrDefault(n => n.Id == id);
if (note != null && note.IsStashed)
{
note.IsStashed = false;
note.LastAccessed = DateTime.UtcNow;
Save(notes);
return note;
}
return null;
}
public static void Discard(Guid id)
{
var notes = Load();
var removed = notes.RemoveAll(n => n.Id == id);
if (removed > 0)
{
Save(notes);
}
}
public static void Update(NoteData note)
{
var notes = Load();
var idx = notes.FindIndex(n => n.Id == note.Id);
if (idx != -1)
{
notes[idx] = note;
}
else
{
notes.Add(note);
}
Save(notes);
}
}