package SQLdemo.com;

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 main extends Activity implements B4AActivity{
	public static main 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;
	private static final boolean fullScreen = false;
	private static final boolean includeTitle = true;
    public static WeakReference<Activity> previousOne;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (isFirst) {
			processBA = new BA(this.getApplicationContext(), null, null, "SQLdemo.com", "main");
			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) {
                anywheresoftware.b4a.keywords.Common.Log("Killing previous instance (main).");
				p.finish();
			}
		}
		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);
        }
		mostCurrent = this;
        processBA.sharedProcessBA.activityBA = null;
		layout = new BALayout(this);
		setContentView(layout);
		afterFirstLayout = false;
		BA.handler.postDelayed(new WaitForLayout(), 5);

	}
	private static class WaitForLayout implements Runnable {
		public void run() {
			if (afterFirstLayout)
				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() {
		activityBA = new BA(this, layout, processBA, "SQLdemo.com", "main");
        processBA.sharedProcessBA.activityBA = new java.lang.ref.WeakReference<BA>(activityBA);
        _activity = new ActivityWrapper(activityBA, "activity");
        anywheresoftware.b4a.Msgbox.isDismissing = false;
        initializeProcessGlobals();		
        initializeGlobals();
        anywheresoftware.b4a.objects.ViewWrapper.lastId = 0;
        anywheresoftware.b4a.keywords.Common.Log("** Activity (main) Create, isFirst = " + isFirst + " **");
        processBA.raiseEvent2(null, true, "activity_create", false, isFirst);
		isFirst = false;
		if (mostCurrent == null || mostCurrent != this)
			return;
        processBA.setActivityPaused(false);
        anywheresoftware.b4a.keywords.Common.Log("** Activity (main) 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);
		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;
	}
	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.raiseEvent(item.getTitle(), eventName + "_click");
			return true;
		}
	}
    public static Class<?> getObject() {
		return main.class;
	}
    private Boolean onKeySubExist = null;
    private Boolean onKeyUpSubExist = null;
	@Override
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
		if (onKeySubExist == null)
			onKeySubExist = processBA.subExists("activity_keypress");
		if (onKeySubExist) {
			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 super.onKeyDown(keyCode, event);
	}
    @Override
	public boolean onKeyUp(int keyCode, android.view.KeyEvent event) {
		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) {
		this.setIntent(intent);
	}
    @Override 
	public void onPause() {
		super.onPause();
        if (_activity == null) //workaround for emulator bug (Issue 2423)
            return;
		anywheresoftware.b4a.Msgbox.dismiss(true);
        anywheresoftware.b4a.keywords.Common.Log("** Activity (main) Pause, UserClosed = " + activityBA.activity.isFinishing() + " **");
        processBA.raiseEvent2(_activity, true, "activity_pause", false, activityBA.activity.isFinishing());		
        processBA.setActivityPaused(true);
        mostCurrent = null;
        if (!activityBA.activity.isFinishing())
			previousOne = new WeakReference<Activity>(this);
        anywheresoftware.b4a.Msgbox.isDismissing = false;
	}

	@Override
	public void onDestroy() {
        super.onDestroy();
		previousOne = 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);
        }
	}
    private static class ResumeMessage implements Runnable {
    	private final WeakReference<Activity> activity;
    	public ResumeMessage(Activity activity) {
    		this.activity = new WeakReference<Activity>(activity);
    	}
		public void run() {
			if (mostCurrent == null || mostCurrent != activity.get())
				return;
			processBA.setActivityPaused(false);
            anywheresoftware.b4a.keywords.Common.Log("** Activity (main) Resume **");
		    processBA.raiseEvent(mostCurrent._activity, "activity_resume", (Object[])null);
		}
    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
	      android.content.Intent data) {
		processBA.onActivityResult(requestCode, resultCode, data);
	}
	private static void initializeGlobals() {
		processBA.raiseEvent2(null, true, "globals", false, (Object[])null);
	}

public anywheresoftware.b4a.keywords.Common __c = null;
public anywheresoftware.b4a.sql.SQL _sql1 = null;
public anywheresoftware.b4a.objects.ListViewWrapper _listviewsql = null;
public anywheresoftware.b4a.objects.ImageViewWrapper _imageviewsql = null;
public static String  _activity_create(boolean _firsttime) throws Exception{
 //BA.debugLineNum = 23;BA.debugLine="Sub Activity_Create(FirstTime As Boolean)";
 //BA.debugLineNum = 25;BA.debugLine="If FirstTime Then";
if (_firsttime) { 
 //BA.debugLineNum = 27;BA.debugLine="If File.Exists (File.DirRootExternal, \"SQLdemo.db\") Then";
if (anywheresoftware.b4a.keywords.Common.File.Exists(anywheresoftware.b4a.keywords.Common.File.getDirRootExternal(),"SQLdemo.db")) { 
 //BA.debugLineNum = 28;BA.debugLine="SQL1.Initialize(File.DirRootExternal, \"SQLdemo.db\", True)";
mostCurrent._sql1.Initialize(anywheresoftware.b4a.keywords.Common.File.getDirRootExternal(),"SQLdemo.db",anywheresoftware.b4a.keywords.Common.True);
 }else {
 //BA.debugLineNum = 30;BA.debugLine="File.Copy(File.DirAssets, \"sqldemo.db\",File.DirRootExternal, \"SQLdemo.db\")";
anywheresoftware.b4a.keywords.Common.File.Copy(anywheresoftware.b4a.keywords.Common.File.getDirAssets(),"sqldemo.db",anywheresoftware.b4a.keywords.Common.File.getDirRootExternal(),"SQLdemo.db");
 //BA.debugLineNum = 31;BA.debugLine="SQL1.Initialize(File.DirRootExternal, \"SQLdemo.db\", True)";
mostCurrent._sql1.Initialize(anywheresoftware.b4a.keywords.Common.File.getDirRootExternal(),"SQLdemo.db",anywheresoftware.b4a.keywords.Common.True);
 };
 };
 //BA.debugLineNum = 36;BA.debugLine="Activity.LoadLayout(\"Main\")";
mostCurrent._activity.LoadLayout("Main",mostCurrent.activityBA);
 //BA.debugLineNum = 37;BA.debugLine="init";
_init();
 //BA.debugLineNum = 39;BA.debugLine="End Sub";
return "";
}
public static String  _activity_pause(boolean _userclosed) throws Exception{
 //BA.debugLineNum = 45;BA.debugLine="Sub Activity_Pause (UserClosed As Boolean)";
 //BA.debugLineNum = 47;BA.debugLine="End Sub";
return "";
}
public static String  _activity_resume() throws Exception{
 //BA.debugLineNum = 41;BA.debugLine="Sub Activity_Resume";
 //BA.debugLineNum = 43;BA.debugLine="End Sub";
return "";
}

public static void initializeProcessGlobals() {
    
    if (processGlobalsRun == false) {
	    processGlobalsRun = true;
		try {
		        main._process_globals();
		
        } catch (Exception e) {
			throw new RuntimeException(e);
		}
    }
}

public static boolean isAnyActivityVisible() {
    boolean vis = false;
vis = vis | (main.mostCurrent != null);
return vis;}
public static String  _globals() throws Exception{
 //BA.debugLineNum = 15;BA.debugLine="Sub Globals";
 //BA.debugLineNum = 17;BA.debugLine="Dim SQL1 As SQL";
mostCurrent._sql1 = new anywheresoftware.b4a.sql.SQL();
 //BA.debugLineNum = 18;BA.debugLine="Dim ListViewSQL As ListView";
mostCurrent._listviewsql = new anywheresoftware.b4a.objects.ListViewWrapper();
 //BA.debugLineNum = 19;BA.debugLine="Dim ImageViewSQL As ImageView";
mostCurrent._imageviewsql = new anywheresoftware.b4a.objects.ImageViewWrapper();
 //BA.debugLineNum = 21;BA.debugLine="End Sub";
return "";
}
public static String  _init() throws Exception{
anywheresoftware.b4a.sql.SQL.CursorWrapper _cursor1 = null;
int _i = 0;
 //BA.debugLineNum = 49;BA.debugLine="Sub init";
 //BA.debugLineNum = 51;BA.debugLine="Dim Cursor1 As Cursor";
_cursor1 = new anywheresoftware.b4a.sql.SQL.CursorWrapper();
 //BA.debugLineNum = 52;BA.debugLine="Cursor1 = SQL1.ExecQuery(\"SELECT name FROM table1\")";
_cursor1.setObject((android.database.Cursor)(mostCurrent._sql1.ExecQuery("SELECT name FROM table1")));
 //BA.debugLineNum = 54;BA.debugLine="For i = 0 To Cursor1.RowCount - 1";
{
final double step26 = 1;
final double limit26 = (int)(_cursor1.getRowCount()-1);
for (_i = (int)(0); (step26 > 0 && _i <= limit26) || (step26 < 0 && _i >= limit26); _i += step26) {
 //BA.debugLineNum = 55;BA.debugLine="Cursor1.Position = i";
_cursor1.setPosition(_i);
 //BA.debugLineNum = 56;BA.debugLine="ListViewSQL.AddTwoLines(Cursor1.GetString(\"name\"),\"item \" & (i + 1))";
mostCurrent._listviewsql.AddTwoLines(_cursor1.GetString("name"),"item "+BA.NumberToString((_i+1)));
 }
};
 //BA.debugLineNum = 59;BA.debugLine="Cursor1.Close";
_cursor1.Close();
 //BA.debugLineNum = 61;BA.debugLine="End Sub";
return "";
}
public static String  _listviewsql_itemclick(int _position,Object _value) throws Exception{
 //BA.debugLineNum = 63;BA.debugLine="Sub ListViewSQL_ItemClick (Position As Int, Value As Object)";
 //BA.debugLineNum = 65;BA.debugLine="ReadBlob(Value)";
_readblob(String.valueOf(_value));
 //BA.debugLineNum = 67;BA.debugLine="End Sub";
return "";
}
public static String  _process_globals() throws Exception{
 //BA.debugLineNum = 11;BA.debugLine="Sub Process_Globals";
 //BA.debugLineNum = 13;BA.debugLine="End Sub";
return "";
}
public static String  _readblob(String _imagename) throws Exception{
anywheresoftware.b4a.sql.SQL.CursorWrapper _cursor1 = null;
byte[] _buffer = null;
anywheresoftware.b4a.objects.streams.File.InputStreamWrapper _ipst = null;
anywheresoftware.b4a.objects.drawable.CanvasWrapper.BitmapWrapper _bitmap1 = null;
int _i = 0;
 //BA.debugLineNum = 69;BA.debugLine="Sub ReadBlob(ImageName As String)";
 //BA.debugLineNum = 71;BA.debugLine="Dim Cursor1 As Cursor";
_cursor1 = new anywheresoftware.b4a.sql.SQL.CursorWrapper();
 //BA.debugLineNum = 72;BA.debugLine="Dim Buffer() As Byte";
_buffer = new byte[(int)(0)];
;
 //BA.debugLineNum = 73;BA.debugLine="Dim IpSt As InputStream";
_ipst = new anywheresoftware.b4a.objects.streams.File.InputStreamWrapper();
 //BA.debugLineNum = 74;BA.debugLine="Dim Bitmap1 As Bitmap";
_bitmap1 = new anywheresoftware.b4a.objects.drawable.CanvasWrapper.BitmapWrapper();
 //BA.debugLineNum = 75;BA.debugLine="Cursor1 = SQL1.ExecQuery(\"SELECT * FROM table1 WHERE name = '\" & ImageName & \"' ;\")";
_cursor1.setObject((android.database.Cursor)(mostCurrent._sql1.ExecQuery("SELECT * FROM table1 WHERE name = '"+_imagename+"' ;")));
 //BA.debugLineNum = 77;BA.debugLine="For i = 0 To Cursor1.RowCount - 1";
{
final double step41 = 1;
final double limit41 = (int)(_cursor1.getRowCount()-1);
for (_i = (int)(0); (step41 > 0 && _i <= limit41) || (step41 < 0 && _i >= limit41); _i += step41) {
 //BA.debugLineNum = 78;BA.debugLine="Cursor1.Position = i";
_cursor1.setPosition(_i);
 }
};
 //BA.debugLineNum = 81;BA.debugLine="Buffer = Cursor1.GetBlob(\"picture\")";
_buffer = _cursor1.GetBlob("picture");
 //BA.debugLineNum = 82;BA.debugLine="IpSt.InitializeFromBytesArray(Buffer, 0, Buffer.Length)";
_ipst.InitializeFromBytesArray(_buffer,(int)(0),_buffer.length);
 //BA.debugLineNum = 83;BA.debugLine="Bitmap1.Initialize2(IpSt)";
_bitmap1.Initialize2((java.io.InputStream)(_ipst.getObject()));
 //BA.debugLineNum = 84;BA.debugLine="IpSt.Close";
_ipst.Close();
 //BA.debugLineNum = 85;BA.debugLine="ImageViewSQL.SetBackgroundImage(Bitmap1)";
mostCurrent._imageviewsql.SetBackgroundImage((android.graphics.Bitmap)(_bitmap1.getObject()));
 //BA.debugLineNum = 86;BA.debugLine="Cursor1.Close";
_cursor1.Close();
 //BA.debugLineNum = 87;BA.debugLine="End Sub";
return "";
}
}
