package com.example.dbsql03;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);
			
			DBAdapter db = new DBAdapter(this);
			
			//---add a contact---
			db.open();
			long id = db.insertContact("Wei-Meng Lee", "weimenglee@learn2develop.net");
			id = db.insertContact("Mary Jackson", "mary@jackson.com");
			db.close();
			
			//---get all contacts---
			db.open();
			Cursor c = db.getAllContacts();
			if (c.moveToFirst())
			{
				do {
					DisplayContact(c);
				} 
				while (c.moveToNext());
			}
			db.close();
			
			
			//---get a contact---
			db.open();
			Cursor cc = db.getContact(2);
			if (cc.moveToFirst())
			DisplayContact(c);
			else
			Toast.makeText(this, "No contact found", Toast.LENGTH_LONG).show();
			db.close();
			
			//---update contact---
			db.open();
			if (db.updateContact(1, "Wei-Meng Lee", "weimenglee@gmail.com"))
			Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show();
			else
			Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show();
			db.close();
			
			//---delete a contact---
			db.open();
			if (db.deleteContact(1))
			Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show();
			else
			Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show();
			db.close();
	}
	
	
	public void DisplayContact(Cursor c)
	{
		Toast.makeText(this,
		"id: " + c.getString(0) + "\n" +
		"Name: " + c.getString(1) + "\n" +
		"Email: " + c.getString(2),
		Toast.LENGTH_LONG).show();
	}
		
		
	// requete select * from current_list where item_id = 1;
	// Cursor c = db.rawQuery(query, null);
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings)
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
