@page "/settings/chapter"
@attribute [Authorize(Roles = AuthRoles.Administrator)]
@using WebApp.Authentication
@using WebApp.Models
@using WebApp.Components.Shared.Components
@using System.Text.Json
@using Core.Models
@inject IWebHostEnvironment Environment
@inject IConfiguration Configuration
@rendermode InteractiveServer
@if (_settings != null)
{
Basic Information
Both (MS and HS)
Middle School (MS)
High School (HS)
Chapter IDs
@if (_isSaving)
{
Saving...
}
else
{
Save Settings
}
@if (!string.IsNullOrEmpty(_statusMessage))
{
@_statusMessage
}
}
else
{
}
@code {
private Models.ChapterSettings? _settings;
private bool _isSaving;
private string? _statusMessage;
private Severity _statusSeverity = Severity.Success;
protected override void OnInitialized()
{
// Load from IConfiguration
_settings = Configuration.GetSection("ChapterSettings").Get()
?? new Models.ChapterSettings();
}
private string GetAppSettingsPath()
{
return Path.Combine(
Environment.ContentRootPath,
"Data",
"appsettings.json");
}
private async Task SaveSettings()
{
if (_settings == null) return;
_isSaving = true;
_statusMessage = null;
try
{
var appSettingsPath = GetAppSettingsPath();
// Ensure Data directory exists
var dataDir = Path.GetDirectoryName(appSettingsPath);
if (dataDir != null && !Directory.Exists(dataDir))
{
Directory.CreateDirectory(dataDir);
}
// Read existing appsettings or create new
JsonDocument? existingDoc = null;
Dictionary settings;
if (File.Exists(appSettingsPath))
{
var existingJson = await File.ReadAllTextAsync(appSettingsPath);
existingDoc = JsonDocument.Parse(existingJson);
settings = JsonSerializer.Deserialize>(existingJson)
?? new Dictionary();
}
else
{
settings = new Dictionary();
}
// Update ChapterSettings section
settings["ChapterSettings"] = _settings;
// Write back to file
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(settings, options);
await File.WriteAllTextAsync(appSettingsPath, json);
existingDoc?.Dispose();
_statusMessage = "Settings saved successfully! Changes will take effect on next application restart.";
_statusSeverity = Severity.Success;
}
catch (Exception ex)
{
_statusMessage = $"Error saving settings: {ex.Message}";
_statusSeverity = Severity.Error;
}
finally
{
_isSaving = false;
}
}
}