package com.merosee.bustrack.driver;


import anywheresoftware.b4a.B4AMenuItem;
import android.app.Activity;
import android.os.Bundle;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BALayout;
import anywheresoftware.b4a.B4AActivity;
import anywheresoftware.b4a.ObjectWrapper;
import anywheresoftware.b4a.objects.ActivityWrapper;
import java.lang.reflect.InvocationTargetException;
import anywheresoftware.b4a.B4AUncaughtException;
import anywheresoftware.b4a.debug.*;
import java.lang.ref.WeakReference;

public class routeselectionfunctions extends Activity implements B4AActivity{
	public static routeselectionfunctions mostCurrent;
	static boolean afterFirstLayout;
	static boolean isFirst = true;
    private static boolean processGlobalsRun = false;
	BALayout layout;
	public static BA processBA;
	BA activityBA;
    ActivityWrapper _activity;
    java.util.ArrayList<B4AMenuItem> menuItems;
	public static final boolean fullScreen = false;
	public static final boolean includeTitle = true;
    public static WeakReference<Activity> previousOne;
    public static boolean dontPause;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        mostCurrent = this;
		if (processBA == null) {
			processBA = new BA(this.getApplicationContext(), null, null, "com.merosee.bustrack.driver", "com.merosee.bustrack.driver.routeselectionfunctions");
			processBA.loadHtSubs(this.getClass());
	        float deviceScale = getApplicationContext().getResources().getDisplayMetrics().density;
	        BALayout.setDeviceScale(deviceScale);
            
		}
		else if (previousOne != null) {
			Activity p = previousOne.get();
			if (p != null && p != this) {
                BA.LogInfo("Killing previous instance (routeselectionfunctions).");
				p.finish();
			}
		}
        processBA.setActivityPaused(true);
        processBA.runHook("oncreate", this, null);
		if (!includeTitle) {
        	this.getWindow().requestFeature(android.view.Window.FEATURE_NO_TITLE);
        }
        if (fullScreen) {
        	getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN,   
        			android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
		
        processBA.sharedProcessBA.activityBA = null;
		layout = new BALayout(this);
		setContentView(layout);
		afterFirstLayout = false;
        WaitForLayout wl = new WaitForLayout();
        if (anywheresoftware.b4a.objects.ServiceHelper.StarterHelper.startFromActivity(this, processBA, wl, false))
		    BA.handler.postDelayed(wl, 5);

	}
	static class WaitForLayout implements Runnable {
		public void run() {
			if (afterFirstLayout)
				return;
			if (mostCurrent == null)
				return;
            
			if (mostCurrent.layout.getWidth() == 0) {
				BA.handler.postDelayed(this, 5);
				return;
			}
			mostCurrent.layout.getLayoutParams().height = mostCurrent.layout.getHeight();
			mostCurrent.layout.getLayoutParams().width = mostCurrent.layout.getWidth();
			afterFirstLayout = true;
			mostCurrent.afterFirstLayout();
		}
	}
	private void afterFirstLayout() {
        if (this != mostCurrent)
			return;
		activityBA = new BA(this, layout, processBA, "com.merosee.bustrack.driver", "com.merosee.bustrack.driver.routeselectionfunctions");
        
        processBA.sharedProcessBA.activityBA = new java.lang.ref.WeakReference<BA>(activityBA);
        anywheresoftware.b4a.objects.ViewWrapper.lastId = 0;
        _activity = new ActivityWrapper(activityBA, "activity");
        anywheresoftware.b4a.Msgbox.isDismissing = false;
        if (BA.isShellModeRuntimeCheck(processBA)) {
			if (isFirst)
				processBA.raiseEvent2(null, true, "SHELL", false);
			processBA.raiseEvent2(null, true, "CREATE", true, "com.merosee.bustrack.driver.routeselectionfunctions", processBA, activityBA, _activity, anywheresoftware.b4a.keywords.Common.Density, mostCurrent);
			_activity.reinitializeForShell(activityBA, "activity");
		}
        initializeProcessGlobals();		
        initializeGlobals();
        
        BA.LogInfo("** Activity (routeselectionfunctions) Create " + (isFirst ? "(first time)" : "") + " **");
        processBA.raiseEvent2(null, true, "activity_create", false, isFirst);
		isFirst = false;
		if (this != mostCurrent)
			return;
        processBA.setActivityPaused(false);
        BA.LogInfo("** Activity (routeselectionfunctions) Resume **");
        processBA.raiseEvent(null, "activity_resume");
        if (android.os.Build.VERSION.SDK_INT >= 11) {
			try {
				android.app.Activity.class.getMethod("invalidateOptionsMenu").invoke(this,(Object[]) null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	public void addMenuItem(B4AMenuItem item) {
		if (menuItems == null)
			menuItems = new java.util.ArrayList<B4AMenuItem>();
		menuItems.add(item);
	}
	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		super.onCreateOptionsMenu(menu);
        try {
            if (processBA.subExists("activity_actionbarhomeclick")) {
                Class.forName("android.app.ActionBar").getMethod("setHomeButtonEnabled", boolean.class).invoke(
                    getClass().getMethod("getActionBar").invoke(this), true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (processBA.runHook("oncreateoptionsmenu", this, new Object[] {menu}))
            return true;
		if (menuItems == null)
			return false;
		for (B4AMenuItem bmi : menuItems) {
			android.view.MenuItem mi = menu.add(bmi.title);
			if (bmi.drawable != null)
				mi.setIcon(bmi.drawable);
            if (android.os.Build.VERSION.SDK_INT >= 11) {
				try {
                    if (bmi.addToBar) {
				        android.view.MenuItem.class.getMethod("setShowAsAction", int.class).invoke(mi, 1);
                    }
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			mi.setOnMenuItemClickListener(new B4AMenuItemsClickListener(bmi.eventName.toLowerCase(BA.cul)));
		}
        
		return true;
	}   
 @Override
 public boolean onOptionsItemSelected(android.view.MenuItem item) {
    if (item.getItemId() == 16908332) {
        processBA.raiseEvent(null, "activity_actionbarhomeclick");
        return true;
    }
    else
        return super.onOptionsItemSelected(item); 
}
@Override
 public boolean onPrepareOptionsMenu(android.view.Menu menu) {
    super.onPrepareOptionsMenu(menu);
    processBA.runHook("onprepareoptionsmenu", this, new Object[] {menu});
    return true;
    
 }
 protected void onStart() {
    super.onStart();
    processBA.runHook("onstart", this, null);
}
 protected void onStop() {
    super.onStop();
    processBA.runHook("onstop", this, null);
}
    public void onWindowFocusChanged(boolean hasFocus) {
       super.onWindowFocusChanged(hasFocus);
       if (processBA.subExists("activity_windowfocuschanged"))
           processBA.raiseEvent2(null, true, "activity_windowfocuschanged", false, hasFocus);
    }
	private class B4AMenuItemsClickListener implements android.view.MenuItem.OnMenuItemClickListener {
		private final String eventName;
		public B4AMenuItemsClickListener(String eventName) {
			this.eventName = eventName;
		}
		public boolean onMenuItemClick(android.view.MenuItem item) {
			processBA.raiseEventFromUI(item.getTitle(), eventName + "_click");
			return true;
		}
	}
    public static Class<?> getObject() {
		return routeselectionfunctions.class;
	}
    private Boolean onKeySubExist = null;
    private Boolean onKeyUpSubExist = null;
	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (processBA.runHook("onkeydown", this, new Object[] {keyCode, event}))
            return true;
		if (onKeySubExist == null)
			onKeySubExist = processBA.subExists("activity_keypress");
		if (onKeySubExist) {
			if (keyCode == anywheresoftware.b4a.keywords.constants.KeyCodes.KEYCODE_BACK &&
					android.os.Build.VERSION.SDK_INT >= 18) {
				HandleKeyDelayed hk = new HandleKeyDelayed();
				hk.kc = keyCode;
				BA.handler.post(hk);
				return true;
			}
			else {
				boolean res = new HandleKeyDelayed().runDirectly(keyCode);
				if (res)
					return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	private class HandleKeyDelayed implements Runnable {
		int kc;
		public void run() {
			runDirectly(kc);
		}
		public boolean runDirectly(int keyCode) {
			Boolean res =  (Boolean)processBA.raiseEvent2(_activity, false, "activity_keypress", false, keyCode);
			if (res == null || res == true) {
                return true;
            }
            else if (keyCode == anywheresoftware.b4a.keywords.constants.KeyCodes.KEYCODE_BACK) {
				finish();
				return true;
			}
            return false;
		}
		
	}
    @Override
	public boolean onKeyUp(int keyCode, android.view.KeyEvent event) {
        if (processBA.runHook("onkeyup", this, new Object[] {keyCode, event}))
            return true;
		if (onKeyUpSubExist == null)
			onKeyUpSubExist = processBA.subExists("activity_keyup");
		if (onKeyUpSubExist) {
			Boolean res =  (Boolean)processBA.raiseEvent2(_activity, false, "activity_keyup", false, keyCode);
			if (res == null || res == true)
				return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	@Override
	public void onNewIntent(android.content.Intent intent) {
        super.onNewIntent(intent);
		this.setIntent(intent);
        processBA.runHook("onnewintent", this, new Object[] {intent});
	}
    @Override 
	public void onPause() {
		super.onPause();
        if (_activity == null)
            return;
        if (this != mostCurrent)
			return;
		anywheresoftware.b4a.Msgbox.dismiss(true);
        if (!dontPause)
            BA.LogInfo("** Activity (routeselectionfunctions) Pause, UserClosed = " + activityBA.activity.isFinishing() + " **");
        else
            BA.LogInfo("** Activity (routeselectionfunctions) Pause event (activity is not paused). **");
        if (mostCurrent != null)
            processBA.raiseEvent2(_activity, true, "activity_pause", false, activityBA.activity.isFinishing());		
        if (!dontPause) {
            processBA.setActivityPaused(true);
            mostCurrent = null;
        }

        if (!activityBA.activity.isFinishing())
			previousOne = new WeakReference<Activity>(this);
        anywheresoftware.b4a.Msgbox.isDismissing = false;
        processBA.runHook("onpause", this, null);
	}

	@Override
	public void onDestroy() {
        super.onDestroy();
		previousOne = null;
        processBA.runHook("ondestroy", this, null);
	}
    @Override 
	public void onResume() {
		super.onResume();
        mostCurrent = this;
        anywheresoftware.b4a.Msgbox.isDismissing = false;
        if (activityBA != null) { //will be null during activity create (which waits for AfterLayout).
        	ResumeMessage rm = new ResumeMessage(mostCurrent);
        	BA.handler.post(rm);
        }
        processBA.runHook("onresume", this, null);
	}
    private static class ResumeMessage implements Runnable {
    	private final WeakReference<Activity> activity;
    	public ResumeMessage(Activity activity) {
    		this.activity = new WeakReference<Activity>(activity);
    	}
		public void run() {
            routeselectionfunctions mc = mostCurrent;
			if (mc == null || mc != activity.get())
				return;
			processBA.setActivityPaused(false);
            BA.LogInfo("** Activity (routeselectionfunctions) Resume **");
            if (mc != mostCurrent)
                return;
		    processBA.raiseEvent(mc._activity, "activity_resume", (Object[])null);
		}
    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
	      android.content.Intent data) {
		processBA.onActivityResult(requestCode, resultCode, data);
        processBA.runHook("onactivityresult", this, new Object[] {requestCode, resultCode});
	}
	private static void initializeGlobals() {
		processBA.raiseEvent2(null, true, "globals", false, (Object[])null);
	}
    public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
        for (int i = 0;i < permissions.length;i++) {
            Object[] o = new Object[] {permissions[i], grantResults[i] == 0};
            processBA.raiseEventFromDifferentThread(null,null, 0, "activity_permissionresult", true, o);
        }
            
    }

public anywheresoftware.b4a.keywords.Common __c = null;
public static String _activeroutename = "";
public static int _activerouteid = 0;
public com.merosee.bustrack.driver.main _main = null;
public com.merosee.bustrack.driver.starter _starter = null;
public com.merosee.bustrack.driver.trackingservice _trackingservice = null;
public com.merosee.bustrack.driver.apimodule _apimodule = null;
public com.merosee.bustrack.driver.httputils2service _httputils2service = null;

public static void initializeProcessGlobals() {
             try {
                Class.forName(BA.applicationContext.getPackageName() + ".main").getMethod("initializeProcessGlobals").invoke(null, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
}
public static String  _globals() throws Exception{
 //BA.debugLineNum = 11;BA.debugLine="Sub Globals";
 //BA.debugLineNum = 13;BA.debugLine="End Sub";
return "";
}
public static String  _loadroutes(Object _targetactivity) throws Exception{
com.merosee.bustrack.driver.httpjob _job = null;
 //BA.debugLineNum = 16;BA.debugLine="Public Sub LoadRoutes(TargetActivity As Object)";
 //BA.debugLineNum = 17;BA.debugLine="Dim job As HttpJob";
_job = new com.merosee.bustrack.driver.httpjob();
 //BA.debugLineNum = 18;BA.debugLine="job.Initialize(\"get_routes\", TargetActivity)";
_job._initialize /*String*/ (processBA,"get_routes",_targetactivity);
 //BA.debugLineNum = 19;BA.debugLine="job.Download(APIModule.ServerURL & \"/get_routes.p";
_job._download /*String*/ (mostCurrent._apimodule._serverurl /*String*/ +"/get_routes.php");
 //BA.debugLineNum = 20;BA.debugLine="APIModule.SetAuthHeader(job, APIModule.GetToken)";
mostCurrent._apimodule._setauthheader /*String*/ (mostCurrent.activityBA,_job,mostCurrent._apimodule._gettoken /*String*/ (mostCurrent.activityBA));
 //BA.debugLineNum = 21;BA.debugLine="End Sub";
return "";
}
public static String  _populaterouteslist(anywheresoftware.b4a.objects.collections.Map _root,anywheresoftware.b4a.objects.ListViewWrapper _lv) throws Exception{
anywheresoftware.b4a.objects.collections.List _routes = null;
anywheresoftware.b4a.objects.collections.Map _colroute = null;
String _rname = "";
String _shift = "";
int _studentcount = 0;
String _secondline = "";
 //BA.debugLineNum = 44;BA.debugLine="Public Sub PopulateRoutesList(Root As Map, lv As L";
 //BA.debugLineNum = 45;BA.debugLine="lv.Clear";
_lv.Clear();
 //BA.debugLineNum = 46;BA.debugLine="If Root.ContainsKey(\"routes\") Then";
if (_root.ContainsKey((Object)("routes"))) { 
 //BA.debugLineNum = 47;BA.debugLine="Dim routes As List = Root.Get(\"routes\")";
_routes = new anywheresoftware.b4a.objects.collections.List();
_routes = (anywheresoftware.b4a.objects.collections.List) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.collections.List(), (java.util.List)(_root.Get((Object)("routes"))));
 //BA.debugLineNum = 49;BA.debugLine="For Each colRoute As Map In routes";
_colroute = new anywheresoftware.b4a.objects.collections.Map();
{
final anywheresoftware.b4a.BA.IterableList group4 = _routes;
final int groupLen4 = group4.getSize()
;int index4 = 0;
;
for (; index4 < groupLen4;index4++){
_colroute = (anywheresoftware.b4a.objects.collections.Map) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.collections.Map(), (java.util.Map)(group4.Get(index4)));
 //BA.debugLineNum = 50;BA.debugLine="Dim rName As String = colRoute.Get(\"route_name\"";
_rname = BA.ObjectToString(_colroute.Get((Object)("route_name")));
 //BA.debugLineNum = 51;BA.debugLine="Dim shift As String = colRoute.Get(\"shift\")";
_shift = BA.ObjectToString(_colroute.Get((Object)("shift")));
 //BA.debugLineNum = 52;BA.debugLine="Dim studentCount As Int = colRoute.Get(\"student";
_studentcount = (int)(BA.ObjectToNumber(_colroute.Get((Object)("student_count"))));
 //BA.debugLineNum = 54;BA.debugLine="Dim secondLine As String = shift.ToUpperCase &";
_secondline = _shift.toUpperCase()+" • "+BA.NumberToString(_studentcount)+" students";
 //BA.debugLineNum = 56;BA.debugLine="lv.AddTwoLines2(rName, secondLine, colRoute)";
_lv.AddTwoLines2(BA.ObjectToCharSequence(_rname),BA.ObjectToCharSequence(_secondline),(Object)(_colroute.getObject()));
 }
};
 //BA.debugLineNum = 59;BA.debugLine="If routes.Size = 0 Then";
if (_routes.getSize()==0) { 
 //BA.debugLineNum = 60;BA.debugLine="Log(\"RouteSelection: No routes found for this b";
anywheresoftware.b4a.keywords.Common.LogImpl("46357008","RouteSelection: No routes found for this bus.",0);
 };
 };
 //BA.debugLineNum = 63;BA.debugLine="End Sub";
return "";
}
public static String  _process_globals() throws Exception{
 //BA.debugLineNum = 5;BA.debugLine="Sub Process_Globals";
 //BA.debugLineNum = 7;BA.debugLine="Public ActiveRouteName As String = \"\"";
_activeroutename = "";
 //BA.debugLineNum = 8;BA.debugLine="Public ActiveRouteID As Int = 0";
_activerouteid = (int) (0);
 //BA.debugLineNum = 9;BA.debugLine="End Sub";
return "";
}
public static String  _setactiveroute(Object _targetactivity,int _routeid,String _routename) throws Exception{
anywheresoftware.b4a.objects.collections.Map _payload = null;
anywheresoftware.b4a.objects.collections.JSONParser.JSONGenerator _gen = null;
com.merosee.bustrack.driver.httpjob _job = null;
 //BA.debugLineNum = 24;BA.debugLine="Public Sub SetActiveRoute(TargetActivity As Object";
 //BA.debugLineNum = 26;BA.debugLine="ActiveRouteID = RouteID";
_activerouteid = _routeid;
 //BA.debugLineNum = 27;BA.debugLine="ActiveRouteName = RouteName";
_activeroutename = _routename;
 //BA.debugLineNum = 29;BA.debugLine="Dim payload As Map";
_payload = new anywheresoftware.b4a.objects.collections.Map();
 //BA.debugLineNum = 30;BA.debugLine="payload.Initialize";
_payload.Initialize();
 //BA.debugLineNum = 31;BA.debugLine="payload.Put(\"route_id\", RouteID)";
_payload.Put((Object)("route_id"),(Object)(_routeid));
 //BA.debugLineNum = 33;BA.debugLine="Dim gen As JSONGenerator";
_gen = new anywheresoftware.b4a.objects.collections.JSONParser.JSONGenerator();
 //BA.debugLineNum = 34;BA.debugLine="gen.Initialize(payload)";
_gen.Initialize(_payload);
 //BA.debugLineNum = 36;BA.debugLine="Dim job As HttpJob";
_job = new com.merosee.bustrack.driver.httpjob();
 //BA.debugLineNum = 37;BA.debugLine="job.Initialize(\"set_active_route\", TargetActivity";
_job._initialize /*String*/ (processBA,"set_active_route",_targetactivity);
 //BA.debugLineNum = 38;BA.debugLine="job.PostString(APIModule.ServerURL & \"/set_active";
_job._poststring /*String*/ (mostCurrent._apimodule._serverurl /*String*/ +"/set_active_route.php",_gen.ToString());
 //BA.debugLineNum = 39;BA.debugLine="APIModule.SetAuthHeader(job, APIModule.GetToken)";
mostCurrent._apimodule._setauthheader /*String*/ (mostCurrent.activityBA,_job,mostCurrent._apimodule._gettoken /*String*/ (mostCurrent.activityBA));
 //BA.debugLineNum = 40;BA.debugLine="End Sub";
return "";
}
}
