#define STD_ASYNC_MODEL
using MonoTouch.UIKit;
using System.Drawing;
using System;
using MonoTouch.Foundation;
using WebServices.www.w3schools.com;

namespace WebServices
{

	public partial class FlipsideViewController : UIViewController
	{
		public FlipsideViewController(string nibName, NSBundle bundle) : base(nibName, bundle)
		{
		}
		
		TempConvert Converter;
		
		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			View.BackgroundColor = UIColor.ViewFlipsideBackgroundColor;
			
			resultLabel.Text = "";
			Converter = new TempConvert();
#if !STD_ASYNC_MODEL
			Converter.CelsiusToFahrenheitCompleted += HandleConverterCelsiusToFahrenheitCompleted;
			Converter.FahrenheitToCelsiusCompleted += HandleConverterFahrenheitToCelsiusCompleted;
#endif
			convertButton.TouchUpInside += HandleConvertButtonTouchUpInside;
			convertButton.TouchUpInside += AnyNonTextControlTouched;
			conversionSelectionButton.ValueChanged += AnyNonTextControlTouched;
		}

		private void AnyNonTextControlTouched(object sender, EventArgs e)
		{
			temperatureTextBox.ResignFirstResponder();
		}
		
#if STD_ASYNC_MODEL
		private void FinishedTemperatureConversion(IAsyncResult asyncResult)
		{
			var fromCelsius = (bool)asyncResult.AsyncState;
			var answer = fromCelsius ? 
				Converter.EndCelsiusToFahrenheit(asyncResult) : Converter.EndFahrenheitToCelsius(asyncResult);
			Converter.EndFahrenheitToCelsius(asyncResult);
			// Since we are running on a separate thread, we can not access UIKit
			// objects from here, so we need to invoke those on the main thread:
			InvokeOnMainThread(() =>
			{
				resultLabel.Text = string.Format(fromCelsius ? "{0}℃ is {1:F2}℉" : "{0}℉ is {1:F2}℃",
					temperatureTextBox.Text, Convert.ToDouble(answer));
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
				activityIndicator.StopAnimating();
			});
		}
#else
		void HandleConverterCelsiusToFahrenheitCompleted(object sender, CelsiusToFahrenheitCompletedEventArgs args)
		{
			InvokeOnMainThread(() =>
			{
				resultLabel.Text = string.Format("{0}℃ is {1:F2}℉", temperatureTextBox.Text, Convert.ToDouble(args.Result));
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
				activityIndicator.StopAnimating();
			});
		}
		
		void HandleConverterFahrenheitToCelsiusCompleted(object sender, FahrenheitToCelsiusCompletedEventArgs args)
		{
			InvokeOnMainThread(() =>
			{
				resultLabel.Text = string.Format("{0}℉ is {1:F2}℃", temperatureTextBox.Text, Convert.ToDouble(args.Result));
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
				activityIndicator.StopAnimating();
			});
		}
#endif
		
		void HandleConvertButtonTouchUpInside(object sender, EventArgs e)
		{
			resultLabel.Text = "";
			double inputTemp;
			if (double.TryParse(temperatureTextBox.Text, out inputTemp))
			{
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
				activityIndicator.StartAnimating();
#if STD_ASYNC_MODEL
				if (conversionSelectionButton.SelectedSegment == 0)
					Converter.BeginCelsiusToFahrenheit(temperatureTextBox.Text, FinishedTemperatureConversion, true);
				else
					Converter.BeginFahrenheitToCelsius(temperatureTextBox.Text, FinishedTemperatureConversion, false);
#else
				if (conversionSelectionButton.SelectedSegment == 0)
					Converter.CelsiusToFahrenheitAsync(temperatureTextBox.Text);
				else
					Converter.FahrenheitToCelsiusAsync(temperatureTextBox.Text);
#endif
			}
			else
				resultLabel.Text = "Invalid input temperature";
		}

		/*
		// Override to allow orientations other than the default portrait orientation.
		public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
		{
			// Return true for supported orientations
			return (InterfaceOrientation == UIInterfaceOrientation.Portrait);
		}
		*/

		public override void DidReceiveMemoryWarning()
		{
			// Releases the view if it doesn't have a superview.
			base.DidReceiveMemoryWarning();
			
			// Release any cached data, images, etc that aren't in use.
		}

		public override void ViewDidUnload()
		{
			// Release any retained subviews of the main view.
			// e.g. this.myOutlet = null;
		}

		partial void done(UIBarButtonItem sender)
		{
			if (Done != null)
				Done(this, EventArgs.Empty);
		}

		public event EventHandler Done;
	}
}

