2023-01-05 15:32:21 +00:00
|
|
|
|
namespace BinaryDad.Notes.Services
|
|
|
|
|
{
|
|
|
|
|
public class FileNoteService : INoteService
|
|
|
|
|
{
|
2023-02-07 17:21:22 +00:00
|
|
|
|
private readonly string? defaultFileName;
|
2023-05-12 16:13:35 +00:00
|
|
|
|
private readonly string? filePath;
|
2023-01-05 15:32:21 +00:00
|
|
|
|
|
|
|
|
|
public FileNoteService(IConfiguration configuration)
|
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
defaultFileName = configuration["DefaultContentFileName"].Trim().ToLower();
|
|
|
|
|
filePath = configuration["ContentFilePath"].Trim();
|
2023-01-05 15:32:21 +00:00
|
|
|
|
|
2023-02-07 17:21:22 +00:00
|
|
|
|
CheckFile(defaultFileName);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string Get(string? noteName)
|
|
|
|
|
{
|
|
|
|
|
CheckFile(noteName);
|
|
|
|
|
|
2023-05-12 16:13:35 +00:00
|
|
|
|
return File.ReadAllText(GetFilePath(noteName));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public ICollection<string> GetNoteNames()
|
|
|
|
|
{
|
|
|
|
|
return Directory.GetFiles(filePath);
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-02-07 17:21:22 +00:00
|
|
|
|
public void Save(string content, string? noteName)
|
2023-01-05 15:32:21 +00:00
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
File.WriteAllText(GetFilePath(noteName), content);
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-02-07 17:21:22 +00:00
|
|
|
|
private void CheckFile(string noteName)
|
2023-01-05 15:32:21 +00:00
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
var filePath = GetFilePath(noteName);
|
2023-02-07 17:21:22 +00:00
|
|
|
|
|
|
|
|
|
// ensure initialized
|
2023-05-12 16:13:35 +00:00
|
|
|
|
if (!File.Exists(filePath))
|
2023-02-07 17:21:22 +00:00
|
|
|
|
{
|
2023-05-12 16:13:35 +00:00
|
|
|
|
Save("Hi! Feel free to start typing. Everything will be saved soon after you are done typing.", noteName);
|
2023-02-07 17:21:22 +00:00
|
|
|
|
}
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
2023-02-07 17:21:22 +00:00
|
|
|
|
|
2023-05-12 16:13:35 +00:00
|
|
|
|
private string GetFilePath(string? noteName)
|
|
|
|
|
{
|
|
|
|
|
noteName = string.IsNullOrWhiteSpace(noteName) ? defaultFileName : noteName;
|
|
|
|
|
|
|
|
|
|
noteName = noteName.Trim().ToLower();
|
|
|
|
|
|
|
|
|
|
return Path.Combine(filePath, noteName);
|
|
|
|
|
}
|
2023-01-05 15:32:21 +00:00
|
|
|
|
}
|
|
|
|
|
}
|