package gr.mybook.mydatabase;

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

public class MainActivity extends Activity {
	EditText textId, textName, textPhone;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textId = (EditText)findViewById(R.id.studentID);
		textName = (EditText)findViewById(R.id.studentName);
		textPhone = (EditText)findViewById(R.id.studentPhone);
	}

	@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;
	}
	
	public void addEntry(View v) {
		MyHelper db = new MyHelper(this, null, null, 1);
		String serial = textId.getText().toString();
		String name = textName.getText().toString();
		String phone = textPhone.getText().toString();
		db.addStudent(serial, name, phone);
		textId.setText("");
		textName.setText("");
		textPhone.setText("");
	}
	
	public void deleteEntry(View v) {
		MyHelper db = new MyHelper(this, null, null, 1);
		String name = textName.getText().toString();
		boolean result = db.deleteStudent(name);
		if (result) {
			textName.setText("");
			Toast.makeText(this, "Student "+name+" deleted", Toast.LENGTH_SHORT).show();
		}
		else {
			Toast.makeText(this, "No match found", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void findEntry(View v) {
		MyHelper db = new MyHelper(this, null, null, 1);
		String name = textName.getText().toString();
		Cursor cursor = db.findStudent(name);
		if (cursor.moveToFirst()) {
			cursor.moveToFirst();
			int id = Integer.parseInt(cursor.getString(0));
			String sId = cursor.getString(1);
			String sName = cursor.getString(2);
			String sPhone = cursor.getString(3);
			textId.setText(sId);
			textName.setText(sName);
			textPhone.setText(sPhone);
		}
		else {
			Toast.makeText(this, "No match found", Toast.LENGTH_SHORT).show();
		}
		cursor.close();
		db.close();
	}
	
	public void updateEntry(View v) {
		MyHelper db = new MyHelper(this, null, null, 1);
		String serial = textId.getText().toString();
		String name = textName.getText().toString();
		String phone = textPhone.getText().toString();
		boolean result = db.updateStudent(serial, name, phone);
		textId.setText("");
		textName.setText("");
		textPhone.setText("");
		if (result) {
			Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
		}
		else {
			Toast.makeText(this, "No match found", Toast.LENGTH_SHORT).show();
		}

	}
}
