using Microsoft.AspNetCore.Components;
using Timer = System.Timers.Timer;
namespace AIStudio.Components;
public partial class ConfigurationText : ConfigurationBase
{
    /// 
    /// The text used for the textfield.
    /// 
    [Parameter]
    public Func Text { get; set; } = () => string.Empty;
    
    /// 
    /// An action which is called when the text was changed.
    /// 
    [Parameter]
    public Action TextUpdate { get; set; } = _ => { };
    /// 
    /// The icon to display next to the textfield.
    /// 
    [Parameter]
    public string Icon { get; set; } = Icons.Material.Filled.Info;
    /// 
    /// The color of the icon to use.
    /// 
    [Parameter]
    public Color IconColor { get; set; } = Color.Default;
    /// 
    /// How many lines should the textfield have?
    /// 
    [Parameter]
    public int NumLines { get; set; } = 1;
    /// 
    /// What is the maximum number of lines?
    /// 
    [Parameter]
    public int MaxLines { get; set; } = 12;
    
    private string internalText = string.Empty;
    private Timer timer = new(TimeSpan.FromMilliseconds(500))
    {
        AutoReset = false
    };
    #region Overrides of ConfigurationBase
    protected override async Task OnInitializedAsync()
    {
        this.timer.Elapsed += async (_, _) => await this.InvokeAsync(async () => await this.OptionChanged(this.internalText));
        await base.OnInitializedAsync();
    }
    #region Overrides of ComponentBase
    protected override async Task OnParametersSetAsync()
    {
        this.internalText = this.Text();
        await base.OnParametersSetAsync();
    }
    #endregion
    #endregion
    private bool AutoGrow => this.NumLines > 1;
    
    private int GetMaxLines => this.AutoGrow ? this.MaxLines : 1;
    private void InternalUpdate(string text)
    {
        this.timer.Stop();
        this.internalText = text;
        this.timer.Start();
    }
    
    private async Task OptionChanged(string updatedText)
    {
        this.TextUpdate(updatedText);
        await this.SettingsManager.StoreSettings();
        await this.InformAboutChange();
    }
}