generated from sindrekjr/AdventOfCodeBase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfig.cs
86 lines (79 loc) · 2.19 KB
/
Config.cs
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
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace AdventOfCode
{
internal class Config
{
private string _c;
private int _y;
private int[] _d;
public string Cookie
{
get => _c;
set
{
if (Regex.IsMatch(value, "^session=[a-z0-9]+$")) _c = value;
}
}
public int Year
{
get => _y;
set
{
if (value >= 2015 && value <= DateTime.Now.Year) _y = value;
}
}
public int[] Days
{
get => _d;
set
{
bool allDaysCovered = false;
_d = value.Where(v =>
{
if (v == 0) allDaysCovered = true;
return v > 0 && v < 26;
}).ToArray();
if (allDaysCovered)
{
_d = new int[] { 0 };
}
else
{
Array.Sort(_d);
}
}
}
private void setDefaults()
{
if (Cookie == default(string)) Cookie = "";
if (Year == default(int)) Year = DateTime.Now.Year;
if (Days == default(int[])) Days = (DateTime.Now.Month == 12) ? new int[] { DateTime.Now.Day } : new int[] { 0 };
}
public static Config Get(string path)
{
var options = new JsonSerializerOptions()
{
IgnoreNullValues = true,
PropertyNameCaseInsensitive = true,
WriteIndented = true
};
Config config;
if (File.Exists(path))
{
config = JsonSerializer.Deserialize<Config>(File.ReadAllText(path), options);
config.setDefaults();
}
else
{
config = new Config();
config.setDefaults();
File.WriteAllText(path, JsonSerializer.Serialize<Config>(config, options));
}
return config;
}
}
}