using System;
using System.Windows.Input;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ControlExplorer.Controls.Tile
{
    public partial class ListBoxSample : UserControl
    {
        public ListBoxSample()
        {
            TileCommand = new DelegateCommand<object>(ExecuteCommand, GetCanExecuteCommand);
            InitializeComponent();
            Loaded += new RoutedEventHandler(OnLoaded);
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            FlickrPhoto.Load("", listBox);
        }

        #region ** Command
        public DelegateCommand<object> TileCommand { get; set; }

        private async void ExecuteCommand(object parameter)
        {
            // show tile content in the preview
            // ((FlickrPhoto)parameter).Content contains Image Uri
            await Launcher.LaunchUriAsync(new Uri(((FlickrPhoto)parameter).Content));
        }

        private bool GetCanExecuteCommand(object parameter)
        {
            return true;
        }
        #endregion

    }

    public class DelegateCommand<T> : ICommand
    {
        private static readonly Action<T> EmptyExecute = (T) => { };
        private static readonly Func<T, bool> EmptyCanExecute = (T) => true;


        private Action<T> _execute;
        private Func<T, bool> _canExecute;

        public DelegateCommand(Action<T> executeMethod)
            : this(executeMethod, null)
        {
        }

        public DelegateCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(T parameter)
        {
            _execute(parameter);
        }


        public bool CanExecute(T parameter)
        {
            return _canExecute(parameter);
        }


        bool ICommand.CanExecute(object parameter)
        {
            return this.CanExecute((T)parameter);
        }


        public event EventHandler CanExecuteChanged;
        public void RaiseCanExecuteChanged()
        {
            var h = this.CanExecuteChanged;
            if (h != null)
            {
                h(this, EventArgs.Empty);
            }
        }


        void ICommand.Execute(object parameter)
        {
            this.Execute((T)parameter);
        }
    }

}
