using System.Windows.Controls;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;
using System.Collections.Generic;
using Telerik.Windows.Controls.GridView;
using System.Windows.Media;
using System.Windows;

namespace RowDetailsInRadWindow
{
    public partial class MainPage : UserControl
    {
        RadWindow window;
        
        public MainPage()
        {
            InitializeComponent();
            
            this.DataContext = new FootballViewModel();

            this.window = new RadWindow();
            this.window.Content = new DetailsPresenter() 
            { 
                // Link the external details presenter to our RadGridView.
                DetailsProvider = this.clubsGrid.RowDetailsProvider 
            };
            this.window.WindowStartupLocation = WindowStartupLocation.Manual;
            this.window.Header = "Players";
            this.window.ResizeMode = ResizeMode.NoResize;
            this.clubsGrid.RowDetailsProvider.PropertyChanged += this.OnRowDetailsProviderPropertyChanged;
        }

        private void OnRowDetailsProviderPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "DataContext")
            {
                // This indicates that selection has changed in RadGridView.
                Club currentClub = this.clubsGrid.RowDetailsProvider.DataContext as Club;
                if (currentClub != null)
                {
                    // A row is selected.
                    var row = this.clubsGrid.ItemContainerGenerator.ContainerFromItem(currentClub) as GridViewRow;
                    Point newLocation = this.CalculateWindowLocation(row);
                    
                    // Show the window next to the row on the right
                    this.window.Left = newLocation.X;
                    this.window.Top = newLocation.Y;
                    
                    this.window.Show();
                }
                else
                {
                    // There is no selection.
                    this.window.Hide();
                }
            }
        }

        private Point CalculateWindowLocation(GridViewRow row)
        {
            var lastCell = row.Cells[row.Cells.Count - 1];
            GeneralTransform generalTransform = lastCell.TransformToVisual(Application.Current.RootVisual);
            return generalTransform.Transform(new Point(lastCell.ActualWidth + 10, 0));
        }
    }
}