
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;

namespace Pages
{
	public partial class BrowserPage : UIViewController
	{
		#region Constructors

		// The IntPtr and initWithCoder constructors are required for items that need 
		// to be able to be created from a xib rather than from managed code

		public BrowserPage(IntPtr handle) : base(handle)
		{
			Initialize();
		}

		[Export("initWithCoder:")]
		public BrowserPage(NSCoder coder) : base(coder)
		{
			Initialize();
		}

		public BrowserPage() : base("BrowserPage", null)
		{
			Initialize();
		}

		void Initialize()
		{
		}
		
		#endregion
		
		private void Alert(string caption, string msg)
		{
			using (UIAlertView av = new UIAlertView(caption, msg, null, "OK", null))
			{
				av.Show();
			}
		}
		
		private void InitButtonsAndTextField()
		{
			backButton.TouchUpInside += (s, e) => { webBrowser.GoBack(); };
			fwdButton.TouchUpInside += (s, e) => { webBrowser.GoForward(); };
			refreshButton.Clicked += (s, e) => { webBrowser.Reload(); };
			urlField.ShouldReturn = (textField) => 
			{
				LoadPage(textField.Text.ToString());
				return textField.ResignFirstResponder(); //Hide keyboard    			
			};
		}
		
		private void InitBrowser()
		{
			webBrowser.LoadStarted += (s, e) => 
			{
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
			};
			webBrowser.LoadFinished += (s, e) => 
			{
			    urlField.Text = webBrowser.Request.Url.AbsoluteString;
			    UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
			};
			webBrowser.LoadError +=  (s, e) => 
			{
			    UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
			    Alert("Browser error", "Web page failed to load: " + e.Error.ToString());
			};
		}
		
		private void LoadPage(string url)
		{
			if (url != "")
			{
				if (!url.StartsWith("http"))
					url = string.Format("http://{0}", url);
				webBrowser.LoadRequest(new NSUrlRequest(new NSUrl(url)));
			}
			//Show the URL that was requested
			urlField.Text = url;
		}
		
		public override void ViewDidLoad()
		{
			base.ViewDidLoad();
			InitButtonsAndTextField();
			InitBrowser();
			//Load a default page
			LoadPage("flickr.com");
		}
	}
}

