namespace Pilz.UI.Dialogs;

public partial class FlyoutBase : UserControl
{
    public DialogResult Result { get; protected set; }
    public bool RegisterDialogAccept { get; set; } = true;
    public bool RegisterDialogCancel { get; set; } = false;

    protected bool ActionPanelVisible
    {
        get => tableLayoutPanel_ActionPanel.Visible;
        set => tableLayoutPanel_ActionPanel.Visible = value;
    }

    protected bool CancelButtonVisible
    {
        get => button_Cancel.Visible;
        set => button_Cancel.Visible = value;
    }

    protected bool CancelButtonEnable
    {
        get => button_Cancel.Enabled;
        set => button_Cancel.Enabled = value;
    }

    protected bool ConfirmButtonEnable
    {
        get => button_Accept.Enabled;
        set => button_Accept.Enabled = value;
    }

    public string Title
    {
        get => label_Title.Text;
        set
        {
            label_Title.Text = value;
            SetShowTitlePanel();
        }
    }

    public FlyoutBase()
    {
        InitializeComponent();
        ParentChanged += FlyoutBase_ParentChanged;

        // Change TabIndex to a very high value
        // -> prevent conflicts with controls based on this class
        button_Cancel.TabIndex = int.MaxValue - 1;
        button_Cancel.TabIndex = int.MaxValue;
    }

    private void FlyoutBase_ParentChanged(object? sender, EventArgs e)
    {
        var frm = FindForm();
        if (frm != null)
        {
            if (RegisterDialogAccept)
                frm.AcceptButton = button_Accept;
            if (RegisterDialogCancel)
                frm.CancelButton = button_Cancel;
        }
    }

    protected void Close(DialogResult result)
    {
        Result = result;

        if (FindForm() is DialogBase dialogForm)
            dialogForm.Close();
    }

    protected virtual bool ValidateOK()
    {
        return true;
    }

    protected virtual void SetShowTitlePanel()
    {
        tableLayoutPanel_TitlePanel.Visible = !string.IsNullOrWhiteSpace(label_Title.Text);
    }

    protected virtual void Button_Accept_Click(object sender, System.EventArgs e)
    {
        if (ValidateOK())
            Close(DialogResult.OK);
    }

    protected virtual void Button_Cancel_Click(object sender, System.EventArgs e)
    {
        Close(DialogResult.Cancel);
    }
}
