using System;

namespace Pilz.Configuration;

public class AutoSaveConfigurationManager : ConfigurationManager
{
    private bool addedHandler = false;
    private bool enableAutoSave = false;
    private string _ConfigFilePath = string.Empty;
    private bool _AutoLoadConfigOnAccess = false;

    public string ConfigFilePath
    {
        get => _ConfigFilePath;
        set
        {
            _ConfigFilePath = value;
            if (AutoLoadConfigOnAccess)
                Load();
        }
    }

    public bool AutoLoadConfigOnAccess
    {
        get => _AutoLoadConfigOnAccess;
        set
        {
            _AutoLoadConfigOnAccess = value;
            if (value)
                Load();
        }
    }

    public bool AutoSaveConfigOnExit
    {
        get => enableAutoSave;
        set
        {
            if (enableAutoSave != value)
            {
                enableAutoSave = value;
                if (enableAutoSave)
                    AddAutoSaveHandler();
                else
                    RemoveAutoSaveHandler();
            }
        }
    }

    private void AddAutoSaveHandler()
    {
        if (!addedHandler)
        {
            AppDomain.CurrentDomain.ProcessExit += AutoSaveSettingsOnExit;
            addedHandler = true;
        }
    }

    private void RemoveAutoSaveHandler()
    {
        AppDomain.CurrentDomain.ProcessExit -= AutoSaveSettingsOnExit;
        addedHandler = false;
    }

    private void AutoSaveSettingsOnExit(object sender, EventArgs e)
    {
        Save();
    }

    private void Save()
    {
        if (!string.IsNullOrEmpty(ConfigFilePath) && Configuration is not null)
            Configuration.WriteToFile(ConfigFilePath);
    }

    private void Load()
    {
        if (!string.IsNullOrEmpty(ConfigFilePath))
            Configuration.ReadFromFile(ConfigFilePath);
    }

    ~AutoSaveConfigurationManager()
    {
        RemoveAutoSaveHandler();
    }
}