package com.example.mobapp_l_database;

import java.util.ArrayList;
import java.util.List;

import com.example.mobapp_l_database.SQLmydict.mydictColumns;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import android.provider.BaseColumns;

public class MainActivity extends ActionBarActivity {

	SQLmydict dbhelp;	// is a singleton
	
	ArrayAdapter<String> spinnerData; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		spinnerData = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item);
		Spinner sp = (Spinner)findViewById(R.id.spinner1);
		sp.setAdapter(spinnerData);

		dbhelp = SQLmydict.getInstance(this);
	}

	@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);
	}

	private class QueryMydict 
		extends AsyncTask<String, Void, ArrayList<Pair<String,String>>> {

        @Override
        protected ArrayList<Pair<String,String>> doInBackground(String... s) {
        		ArrayList<Pair<String,String>> rc = new ArrayList<Pair<String,String>>();
        		try {
		        	SQLiteDatabase db = dbhelp.getWritableDatabase();
		    		String[] tableColumns = new String[] {
		    				SQLmydict.mydictColumns._ID,
		    				SQLmydict.mydictColumns.COLUMN_NAME_KEY,
		    				SQLmydict.mydictColumns.COLUMN_NAME_VALUE
		    		};
		    		String whereClause = SQLmydict.mydictColumns.COLUMN_NAME_KEY+" like ?";
		    		String[] whereArgs = new String[] { s[0] };
		    		String orderBy = SQLmydict.mydictColumns.COLUMN_NAME_KEY;
		    		Cursor c = db.query(SQLmydict.mydictColumns.TABLE_NAME, 
		    				tableColumns, whereClause, whereArgs,
		    		        null, null, orderBy);
		    		if (c.moveToFirst()) {
		    			//Integer idxId  = c.getColumnIndex(SQLmydict.mydictColumns._ID);
		    			Integer idxKey = c.getColumnIndex(SQLmydict.mydictColumns.COLUMN_NAME_KEY);
		    			Integer idxVal = c.getColumnIndex(SQLmydict.mydictColumns.COLUMN_NAME_VALUE);
		    			 
	    	            do {
	    	            		rc.add(new Pair<String, String>(c.getString(idxKey), c.getString(idxVal)));
	    	            } while (c.moveToNext());
	    	        }
	    	        if (c != null && !c.isClosed()) {
	    	            c.close();
	    	        }
	    		} catch (SQLException e) {
	    			rc.clear();
	    			// for simplicity
	    			rc.add(new Pair<String, String>("__exc__", e.toString()));
	    		}
        		return rc;
        }

        @Override
        protected void onPostExecute(ArrayList<Pair<String,String>> rc) {
			TextView textView = (TextView)findViewById(R.id.textView3);
			spinnerData.clear();
			if (rc.size()==1 && rc.get(0).first.equals("__exc__")) {
	   			textView.setText("rc NOK ");
	   			Toast.makeText(textView.getContext(), rc.get(0).second, Toast.LENGTH_SHORT).show();   				
			} else {
				for (int i=0; i<rc.size(); ++i)
	   				spinnerData.add(rc.get(i).first + ":" + rc.get(i).second);
				spinnerData.notifyDataSetChanged();
				textView.setText("rc OK, rows="+rc.size());
			}
        }
    }	

	public void onGet(View v) {
		EditText edit1 = (EditText)findViewById(R.id.editText1);
		// get asynchronously
		new QueryMydict().execute(edit1.getText().toString());		
	}
	
	private class InsertMydict extends AsyncTask<ContentValues, Void, Pair<Long,String>> {

        @Override
        protected Pair<Long,String> doInBackground(ContentValues... cvs) {
	    		try {
		        	SQLiteDatabase db = dbhelp.getWritableDatabase();
				Long newRowId = db.insertOrThrow(
					SQLmydict.mydictColumns.TABLE_NAME, null, cvs[0]);
	            return new Pair<Long, String>(newRowId,"");
	    		} catch (SQLException e) {
	    			return new Pair<Long, String>(-1L,e.toString());
	    		}
        }

        @Override
        protected void onPostExecute(Pair<Long,String> rc) {
			TextView textView = (TextView)findViewById(R.id.textView3);
        		if (rc.first>=0) {
        			textView.setText("rc OK, row="+rc.first);
        		} else {
        			textView.setText("rc NOK ");
        			Toast.makeText(textView.getContext(), rc.second, Toast.LENGTH_SHORT).show();
        		}
        }
    }	

	public void onSet(View v) {
		EditText edit1 = (EditText)findViewById(R.id.editText1);
		EditText edit2 = (EditText)findViewById(R.id.editText2);
		
		ContentValues cv = new ContentValues();
		cv.put(SQLmydict.mydictColumns.COLUMN_NAME_KEY, edit1.getText().toString());
		cv.put(SQLmydict.mydictColumns.COLUMN_NAME_VALUE, edit2.getText().toString());

		// insert asynchronously
		new InsertMydict().execute(cv);		
	}
	
	public void onClear(View v) {
		TextView textView = (TextView)findViewById(R.id.textView3);
		EditText edit1 = (EditText)findViewById(R.id.editText1);
		try {
			// for simplicity delete objects here
			SQLiteDatabase db = dbhelp.getWritableDatabase();
			String whereClause = SQLmydict.mydictColumns.COLUMN_NAME_KEY+" like ?";
			String[] whereArgs = new String[] {edit1.getText().toString()};

			Integer rows = db.delete(SQLmydict.mydictColumns.TABLE_NAME, 
					whereClause , whereArgs);

			textView.setText("rc OK, rows="+rows);			
		} catch (SQLException e) {
			textView.setText("rc NOK ");
			Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
		}
	}
	
	public void onDrop(View v) {
		TextView textView = (TextView)findViewById(R.id.textView3);
		try {
			// for simplicity drop table here
			SQLiteDatabase db = dbhelp.getWritableDatabase();
			db.execSQL(SQLmydict.MYDICT_TABLE_DROP);
			db.execSQL(SQLmydict.MYDICT_TABLE_CREATE);
			textView.setText("rc OK");			
		} catch (SQLException e) {
			textView.setText("rc NOK ");
			Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
		}
	}
}
