using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using C1.Silverlight;

namespace C1HtmlHost_Browser
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            // set ViewModel
            DataContext = new ViewModel();
        }

        // This can be made with a Behavior if we wanted to follow 
        // an orthodox approach to MVVM
        private void C1TextBoxBase_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                var txt = (C1TextBoxBase)sender;
                (DataContext as ViewModel).SearchCommand.Execute(txt.Text);
            }
        }
    }

    public class ViewModel
        :INotifyPropertyChanged
    {
        public ViewModel()
        {
            UriAddress = new Uri(Address, UriKind.Absolute);
            SearchCommand = new C1DelegateCommand(
                p =>
                {
                    UriAddress = new Uri(Address, UriKind.Absolute);
                },
                p =>
                {
                    return Uri.IsWellFormedUriString(_address, UriKind.Absolute);
                });
        }

        private string _address = "http://www.componentone.com";
        public string Address
        {
            get
            {
                return _address;
            }
            set
            {
                _address = value;
                RaisePropertyChanged("Address");
                (SearchCommand as C1DelegateCommand).RaiseCanExecuteChanged();
            }
        }

        private Uri _uriAddress;
        public Uri UriAddress
        {
            get
            {
                return _uriAddress;
            }
            set
            {
                _uriAddress = value;
                RaisePropertyChanged("UriAddress");
            }
        }

        public ICommand SearchCommand { get; private set; }

        protected void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
