using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Life.Automaton;
using Life.ViewModel;

namespace Life
{
    public partial class AutomatonField : UserControl
    {
        #region Dependency Property Wrappers
        public int Size
        {
            get { return (int) GetValue(SizeProperty); }
            set { SetValue(SizeProperty, value); }
        }

        public int Separation
        {
            get { return (int) GetValue(SeparationProperty); }
            set { SetValue(SeparationProperty, value); }
        }

        public IField Field
        {
            get { return (IField) GetValue(FieldProperty); }
            set { SetValue(FieldProperty, value); }
        }

        public ICommand ClickCommand
        {
            get { return (ICommand) GetValue(ClickCommandProperty); }
            set { SetValue(ClickCommandProperty, value); }
        }
        #endregion
        
        public FieldViewModel ViewModel { get; set; } = new FieldViewModel();
        
        public AutomatonField()
        {
            InitializeComponent();
        }

        private static void OnFieldChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var field = d as AutomatonField;
            
            field.ViewModel.Field = e.NewValue as IField;
        }

        private static void OnSizeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var field = d as AutomatonField;
            
            field.ViewModel.Size = (int)e.NewValue;
        }

        private static void OnSeparationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var field = d as AutomatonField;
            
            field.ViewModel.Separation = (int)e.NewValue;
        }
        
        #region Dependency Properties
        public static readonly DependencyProperty SizeProperty = DependencyProperty.Register(
            nameof(Size), 
            typeof(int), typeof(AutomatonField),
             new PropertyMetadata(OnSizeChanged)
        );
        
        public static readonly DependencyProperty SeparationProperty = DependencyProperty.Register(
            nameof(Separation), 
            typeof(int), typeof(AutomatonField),
            new PropertyMetadata(OnSeparationChanged)
        );

        public static readonly DependencyProperty FieldProperty = DependencyProperty.Register(
            nameof(Field), 
            typeof(IField), typeof(AutomatonField),
            new PropertyMetadata(OnFieldChanged)
        );

        public static readonly DependencyProperty ClickCommandProperty = DependencyProperty.Register(
            nameof(ClickCommand), 
            typeof(ICommand), typeof(AutomatonField)
        );

        #endregion
    }
}