package com.example.eg17_2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	
	private String mPath;
	private TextView textView;
	
	private ToDoDBAdapter dbAdapter = null;
	
	private int mRowIndex = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		textView = (TextView) findViewById(R.id.label);
		
		Button button1 = (Button)findViewById(R.id.btn_create);
		button1.setOnClickListener(this);
		
		Button button2 = (Button)findViewById(R.id.btn_insert);
		button2.setOnClickListener(this);
		
		Button button3 = (Button)findViewById(R.id.btn_modify);
		button3.setOnClickListener(this);
		
		Button button4 = (Button)findViewById(R.id.btn_delete);
		button4.setOnClickListener(this);
		
		Button button5 = (Button)findViewById(R.id.btn_select);
		button5.setOnClickListener(this);
	}
	
	public void onClick(View v) {
 		switch(v.getId()){
     	 case R.id.btn_create:
     		dbAdapter = new ToDoDBAdapter(MainActivity.this);
    		mPath = dbAdapter.open();
    		textView.setText("创建数据库成功, 数据库路径为: " + mPath);
      	 	break;
      	 	
     	 case R.id.btn_insert:
     		if (dbAdapter == null) {
    			textView.setText("数据库不存在, 请点击'创建数据库'按钮.");
    		} else {
    			TodoItem item = new TodoItem("任务1");
    			dbAdapter.insertTask(item);
    			textView.setText("插入数据成功");
    			mRowIndex++;
    		}
      	 	break;
      	 	
     	 case R.id.btn_modify:
     		if (dbAdapter == null) {
    			textView.setText("数据库不存在, 请点击'创建数据库'按钮.");
    		} else {
    			dbAdapter.updateTask(mRowIndex, "任务1-改");
    			textView.setText("修改数据成功");
    		}
      	 	break;
      	 	
     	 case R.id.btn_delete:
     		if (dbAdapter == null) {
    			textView.setText("数据库不存在, 请点击'创建数据库'按钮.");
    		} else {
    			dbAdapter.removeTask(mRowIndex);
    			textView.setText("删除数据成功");
    		}
      	 	break;
      	 	
     	case R.id.btn_select:
     		if (dbAdapter == null) {
    			textView.setText("数据库不存在, 请点击'创建数据库'按钮.");
    		} else {
    			TodoItem item = dbAdapter.getToDoItem(mRowIndex);
    			if (item == null) {
    				textView.setText("数据库不存在, 请点击'插入数据'按钮.");
				} else {
					textView.setText("查询数据成功: " + item.toString());
				}
    		}
      	 	break;
 		}
	}
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (dbAdapter != null) {
			dbAdapter.close();
			dbAdapter = null;
		}
	}
}
