﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Muffelsausen.MuffelsausenApp.Views.CompetitionManagement.PackBag
{
    /// <summary>
    /// Interaktionslogik für PackBagRoutinesHostTemplate.xaml
    /// </summary>
    public partial class PackBagRoutinesHostTemplate : UserControl
    {
        public PackBagRoutinesHostTemplate()
        {
            InitializeComponent();
        }

        private void RoutinesDataGrid_GotFocus(object sender, RoutedEventArgs e)
        {
            if (e.OriginalSource.GetType() == typeof(DataGridCell))
            {
                DataGrid dataGrid = (DataGrid)sender;
                dataGrid.BeginEdit(e);

                var control = GetFirstChildByType<Control>(e.OriginalSource as DataGridCell);
                if (control != null)
                {
                    control.Focus();
                }
            }
        }

        private T GetFirstChildByType<T>(DependencyObject prop) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(prop); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild((prop), i) as DependencyObject;
                if (child == null)
                {
                    continue;
                }

                T castedProp = child as T;
                if (castedProp != null)
                {
                    return castedProp;
                }

                castedProp = GetFirstChildByType<T>(child);

                if (castedProp != null)
                {
                    return castedProp;
                }
            }
            return null;
        }
    }
}
