using System.Diagnostics;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Diagrams;
using Telerik.Windows.Controls.Diagrams.Extensions;

namespace ExportToPDF_SL
{
    public partial class MainPage : UserControl
    {
        private FileManager fileManager;

        static MainPage()
        {
            var saveBinding = new CommandBinding(DiagramCommands.Save, ExecuteSave, CanExecutedSave);
            var openBinding = new CommandBinding(DiagramCommands.Open, ExecuteOpen);

            CommandManager.RegisterClassCommandBinding(typeof(MainPage), saveBinding);
            CommandManager.RegisterClassCommandBinding(typeof(MainPage), openBinding);
        }

        public MainPage()
        {
            InitializeComponent();

            this.fileManager = new FileManager(this.diagram);

            this.connection.ConnectionPoints.Add(new System.Windows.Point(125, 100));
        }

        private static void CanExecutedSave(object sender, CanExecuteRoutedEventArgs e)
        {
            var owner = sender as MainPage;
            e.CanExecute = owner != null && owner.diagram != null && owner.diagram.Items.Count > 0;
        }

        private static void ExecuteSave(object sender, ExecutedRoutedEventArgs e)
        {
            var owner = sender as MainPage;
            if (owner != null)
                owner.fileManager.SaveToFile();
        }

        private static void ExecuteOpen(object sender, ExecutedRoutedEventArgs e)
        {
            var owner = sender as MainPage;
            if (owner != null)
            {
                owner.fileManager.LoadFromFile();
            }
        }

        private void diagram_Drag(object sender, DragRoutedEventArgs e)
        {
            var connection = e.Items.OfType<RadDiagramConnection>().FirstOrDefault();

            if (connection != null)
            {
                Debug.WriteLine(connection.Position);
            }
        }
    }
}
