using BookReader.Models;
using System.Globalization;

namespace BookReader.Services;

public class SettingsService : ISettingsService
{
    private readonly IDatabaseService _databaseService;

    public SettingsService(IDatabaseService databaseService)
    {
        _databaseService = databaseService;
    }

    public async Task<string> GetAsync(string key, string defaultValue = "")
    {
        var value = await _databaseService.GetSettingAsync(key);
        return value ?? defaultValue;
    }

    public async Task SetAsync(string key, string value)
    {
        await _databaseService.SetSettingAsync(key, value);
    }

    public async Task<int> GetIntAsync(string key, int defaultValue = 0)
    {
        var value = await _databaseService.GetSettingAsync(key);
        if (int.TryParse(value, out var result))
        {
            return result;
        }

        return defaultValue;
    }

    public async Task SetIntAsync(string key, int value)
    {
        await _databaseService.SetSettingAsync(key, value.ToString(CultureInfo.InvariantCulture));
    }

    public async Task<double> GetDoubleAsync(string key, double defaultValue = 0)
    {
        var value = await _databaseService.GetSettingAsync(key);
        if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
        {
            return result;
        }

        return defaultValue;
    }

    public async Task SetDoubleAsync(string key, double value)
    {
        await _databaseService.SetSettingAsync(key, value.ToString(CultureInfo.InvariantCulture));
    }

    public async Task<Dictionary<string, string>> GetAllAsync()
    {
        return await _databaseService.GetAllSettingsAsync();
    }

    public async Task SetSecurePasswordAsync(string password)
    {
        await SecureStorage.Default.SetAsync(SecureStorageKeys.CalibrePassword, password);
    }

    public async Task<string> GetSecurePasswordAsync()
    {
        return await SecureStorage.Default.GetAsync(SecureStorageKeys.CalibrePassword) ?? string.Empty;
    }

    public async Task ClearSecurePasswordAsync()
    {
        SecureStorage.Default.Remove(SecureStorageKeys.CalibrePassword);
        await Task.CompletedTask;
    }
}

