﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Threading;
using System.Net;
using Android.Webkit;

namespace WalletFinder
{
	[Activity (Label = "Tracking")]			
	public class Tracking : Activity
	{
		public string[] login_data = new string[] { };
		public string[] creds = new string[] { };

		public string walletImei = "";
		public string walletLoc = "";
		public string walletBattery = "";
		public string walletName = "";

		public static WebView trackingView;
		public static WebView loadingView;
		public WebViewClient web = new CWebViewClient();

		protected override void OnCreate (Bundle savedInstanceState)
		{
			base.OnCreate (savedInstanceState);

			SetContentView (Resource.Layout.TrackingLayout);

			login_data = Intent.GetStringArrayExtra ("login_data");
			creds = Intent.GetStringArrayExtra ("credentials");
			walletName = Intent.GetStringExtra ("walletName");
			walletBattery = Intent.GetStringExtra ("walletBattery");
			walletLoc = Intent.GetStringExtra ("walletLoc");
			walletImei = Intent.GetStringExtra ("walletImei");

			trackingView = FindViewById<WebView> (Resource.Id.trackingWeb);
			loadingView = FindViewById<WebView> (Resource.Id.loadinView);

			loadingView.SetWebViewClient (new WebViewClient());
			loadingView.LoadUrl(string.Format("file:///android_asset/loading.html"));

			this.Title = ("Locate Wallet");

			Thread t = new Thread (Loader);
			t.Start ();
		}

		void Loader ()
		{
			Thread.Sleep (3000);
			RunOnUiThread (() => {
				trackingView.SetWebViewClient (web);
				trackingView.Settings.JavaScriptEnabled = true;
				trackingView.LoadUrl ("http://wallet.stardebris.net/track_wallet_mobile.php?session=" + login_data [1] + "&imei=" + walletImei);
			});
		}

		private class CWebViewClient : WebViewClient
		{
			public override void OnPageStarted (WebView view, string url, Android.Graphics.Bitmap favicon)
			{
				base.OnPageStarted (view, url, favicon);
			}

			public override void OnPageFinished (WebView view, string url)
			{
				base.OnPageFinished (view, url);
				loadingView.Visibility = ViewStates.Gone;
			}

			public override void OnReceivedError (WebView view, ClientError errorCode, string description, string failingUrl)
			{
				Toast.MakeText (view.Context, "Error " + errorCode + ": " + description, ToastLength.Long).Show ();
				base.OnReceivedError (view, errorCode, description, failingUrl);
				loadingView.LoadUrl(string.Format("file:///android_asset/error.html"));
				trackingView.LoadUrl(string.Format("file:///android_asset/error.html"));
			}
		}
	}
}

