using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;

namespace MultiDispatcherTest
{
	public class MainWindowViewModel : INotifyPropertyChanged
	{
		public event PropertyChangedEventHandler PropertyChanged;

		private RelayCommand _childOpenCommand;

		public ICommand ChildOpenCommand
		{
			get { return this._childOpenCommand ?? (this._childOpenCommand = new RelayCommand(ExecuteChildOpen)); }
		}

		private static int _createdNum;

		private void ExecuteChildOpen(object obj)
		{
			_createdNum++;
			var entrance = new UIEntrance(_createdNum.ToString());
			entrance.Post(async d =>
			{
				Debug.WriteLine("[shwlee] `````` seq : " + _createdNum);

				var result = await OpenWindowProcess();

				Debug.WriteLine("[shwlee] seq : " + _createdNum + ", result : " + result);

			},null);
		}

		private async Task<int> OpenWindowProcess()
		{
			Debug.WriteLine("[shwlee] $$$$$$$ seq : " + _createdNum);

			var cal = 0;
			await TaskEx.Run(() =>
			{
				for (int i = 0; i < 100; i++)
				{
					Thread.Sleep(1);
					cal += i;
				}
			});

			var childWindow = new ChildWindow();
			childWindow.Closed += (s, e) => Dispatcher.CurrentDispatcher.InvokeShutdown();
			childWindow.Show();

			Debug.WriteLine("[shwlee] ~~~~~ seq : " + _createdNum);

			return cal;
		}
	}
}
