using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;

namespace QC.QTMApplication;

public class WPFTextBoxPopup
{
	public delegate void PreviewPopupKeyDown(object sender, KeyEventArgs e);

	private Popup popup;

	private TextBox childTextBox;

	public PreviewPopupKeyDown OnPreviewPopupKeyDown;

	private TextBox parentTextBox;

	public bool IsOpen
	{
		set
		{
			popup.IsOpen = value;
		}
	}

	public WPFTextBoxPopup()
	{
		popup = new Popup();
		ScrollViewer scrollViewer = new ScrollViewer();
		childTextBox = new TextBox();
		childTextBox.AcceptsReturn = true;
		childTextBox.PreviewKeyDown += childTextBox_PreviewKeyDown;
		childTextBox.TextWrapping = TextWrapping.Wrap;
		childTextBox.Loaded += childTextBox_Loaded;
		childTextBox.LostFocus += childTextBox_LostFocus;
		scrollViewer.Content = childTextBox;
		popup.Child = scrollViewer;
	}

	private void childTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
	{
		RaisePreviewOnKeyDown(sender, e);
	}

	private void childTextBox_LostFocus(object sender, RoutedEventArgs e)
	{
		IsOpen = false;
	}

	private void childTextBox_Loaded(object sender, RoutedEventArgs e)
	{
		Keyboard.Focus(childTextBox);
		childTextBox.Focus();
	}

	public void SetParentTextBox(TextBox parentTextBox)
	{
		this.parentTextBox = parentTextBox;
		popup.Width = this.parentTextBox.ActualWidth + 100.0;
		popup.Height = this.parentTextBox.ActualHeight + 200.0;
		popup.PlacementTarget = this.parentTextBox;
		popup.Placement = PlacementMode.Bottom;
		popup.VerticalOffset = 0.0 - this.parentTextBox.ActualHeight;
		Binding binding = new Binding("Text");
		binding.Source = this.parentTextBox;
		binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
		childTextBox.SetBinding(TextBox.TextProperty, binding);
		Binding binding2 = new Binding("IsKeyboardFocused");
		binding2.Source = this.parentTextBox;
		popup.SetBinding(Popup.StaysOpenProperty, binding2);
	}

	public TextBox GetParentTextBox()
	{
		return parentTextBox;
	}

	private void RaisePreviewOnKeyDown(object sender, KeyEventArgs e)
	{
		if (OnPreviewPopupKeyDown != null)
		{
			OnPreviewPopupKeyDown(sender, e);
		}
	}
}
