package com.usai.redant.raimage;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.usai.redant.redantmobile.R;
import com.usai.redant.util.Network;
import com.usai.redant.util.dbgUtil;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class UploadQueueActivity extends ListActivity
{
	private SQLiteDatabase m_db = null;
	private Cursor m_cursor = null;
	RecordsAdapter m_listadapter;
	private TextView m_tvalert;
	Timer timer = new Timer();
	TimerTask task = new TimerTask()
	{
		boolean change = false;
		public void run()
		{
		 
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					if (change)
					{
						change = false;
						m_tvalert.setTextColor(Color.TRANSPARENT); // 这个是透明，=看不到文字
					}
					else
					{
						change = true;
						m_tvalert.setTextColor(getResources().getColor(
								R.color.message_success));
					}
				}
			});
		}
	};
	public class RecordsAdapter extends SimpleCursorAdapter
	{


		public RecordsAdapter(Context context, int layout, Cursor c,
                              String[] from, int[] to)
		{
			
			super(context, layout, c, from, to);
			// TODO Auto-generated constructor stub
		}

		

		@Override
		public void bindView(View view, Context context, Cursor cursor)
		{
			 String path = cursor.getString(3);
			 int err_code = cursor.getInt(1);

			File f = new File(path);
			final String filename=f.getName();
		
			final TextView filetext = (TextView) view.findViewById(R.id.filename);
			filetext.setText(filename);
			
			final TextView err_codetext = (TextView) view.findViewById(R.id.err_code);
			switch (err_code)
			{
				case Network.RESULT_LOCALFILE_ERROR:
					err_codetext.setText("Local file error.");
					break;
				case Network.RESULT_NET_ERROR:
					err_codetext.setText("Network error.");
					break;
				case Network.RESULT_USERAUTH_ERROR:
					err_codetext.setText("User authorization error.");
					break;
				case Network.RESULT_ERROR:
					err_codetext.setText("Unknown error.");
					break;
				case Network.RESULT_FALSE:
					err_codetext.setText("Upload failed.");
					break;
				case Network.STATUS_WAIT:
					err_codetext.setText("Wait for upload.");
					break;
			
				default:
					break;
			}
			super.bindView(view, context, cursor);

	

		}

	}

	@Override
	protected void onDestroy()
	{
		unregisterReceiver(UploadQueueReceiver);
//		dbUtil.CloseDB(m_db);
		super.onDestroy();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.uploadqueue, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO Auto-generated method stub
		switch (item.getItemId())
		{
			case R.id.action_clearfailed:
				dbgUtil.fileLog("menu item clear click , clear...");
			//	clear();
				
				
				new AlertDialog.Builder(
						UploadQueueActivity.this)
						.setIconAttribute(
								android.R.attr.alertDialogIcon)
						.setTitle(
								R.string.confirm_to_delete)
						.setMessage(
								"Are you sure to clear error records?")
						.setPositiveButton(
								android.R.string.ok,
								new DialogInterface.OnClickListener()
								{
									public void onClick(
											DialogInterface dialog,
											int whichButton)
									{
										
//										SQLiteDatabase dbr = dbUtil.OpenDB(UploadQueueActivity.this, null, false);
//										Cursor cursor = dbr.query("pics", new String[] { "_id",
//												"local_path" }, "try_count>=3", null, null, null, "_id", null);
//										while (cursor.moveToNext())
//										{
//											int _id = cursor.getInt(0);
//											String path = cursor.getString(1);
//
//
//											RedAntApplication.writeLock.lock();
//
//											// write sql process
//											SQLiteDatabase dbw = dbUtil.OpenDB(UploadQueueActivity.this,
//													null, true);
//											dbw.execSQL("delete from pics where _id= "+_id);
//
//											String timeStamp = new SimpleDateFormat("yyyy_MM_dd")
//													.format(new Date());
//
//											File storageDir = new File(Environment
//													.getExternalStorageDirectory().getPath()
//													+ "/redant/pop/done/" + timeStamp);
//
//											if (!storageDir.exists())
//												storageDir.mkdirs();
//
//											File pic = new File(path);
//
//											pic.delete();
//											dbUtil.CloseDB(dbw);
//											RedAntApplication.writeLock.unlock();
//
//										}
//
//										dbUtil.CloseCursor(cursor);
//										dbUtil.CloseDB(dbr);

										sendBroadcast(new Intent("REDANT.POP.UPDATE_QUEUE_VIEW"));
										sendBroadcast(new Intent("REDANT.POP.CLEAR_UPLOAD_QUEUE"));
									}
								})
						.setNegativeButton(
								android.R.string.cancel,
								new DialogInterface.OnClickListener()
								{
									public void onClick(
											DialogInterface dialog,
											int whichButton)
									{
										// debug
										// update_location();
									}
								})
						.create()
						.show();
				break;

			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
//		user = ApexTrackingApplication.get_user();
//		
//		password = ApexTrackingApplication.get_pass();
//		function_name = getIntent().getStringExtra("function_name");
		setContentView(R.layout.activity_search);
//		m_db = dbUtil.OpenDB(this, null, true);
		// m_TextView = (TextView) findViewById(R.id.summarytext);
		// m_TextView.setText(getString(m_Activityinfo.TextViewValue));
		// m_ListView = (ListView) findViewById(android.R.id.list);
		m_cursor = m_db.query("pics", new String[] { "picker",
				"err_code", "pid", "local_path","_id" }, null, null, null, null,
				"_id", null);
		startManagingCursor(m_cursor);
		m_listadapter = new RecordsAdapter(this,
		// Use a template that displays a text view
				R.layout.search_lvitem_edit,
				// Give the cursor to the list adatper
				m_cursor,
				// Map the NAME column in the people database to...
				new String[] { "pid",  "picker" },
				// The "text1" view defined in the XML template
				new int[] { R.id.pidval, R.id.picker });
		setListAdapter(m_listadapter);
//		Button btnok = (Button) findViewById(R.id.btnok);
//		btnok.setOnClickListener(this);
//		Button btncancel = (Button) findViewById(R.id.btncancel);
//		btncancel.setOnClickListener(this);
//
//		SharedPreferences RunOnce = getSharedPreferences("Apex", 0);

//		String vername;
//		try
//		{
//			vername = getPackageManager().getPackageInfo("com.usai.apex", 0).versionName;
//			boolean bFirstRun = RunOnce.getBoolean("FirstRun" + vername
//					+ "_search", true);
//			if (bFirstRun)
//			{
//				SharedPreferences.Editor editor = RunOnce.edit();
//				editor.putBoolean("FirstRun" + vername + "_search", false);
//				// Don't forget to commit your edits!!!
//				editor.commit();
//				Intent intent = new Intent();
//				intent.setClass(this, HelpActivity.class);
//				intent.putExtra("caller", "search");
//				startActivity(intent);
//
//			}
//		}
//		catch (NameNotFoundException e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		// initlist();

		// m_ListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		// m_listadapter = new FieldsAdapter(this, data, resource, from, to);

		// m_listadapter = new RecordsAdapter(this,
		// // Use a template that displays a text view
		// m_iListItemID,
		// // Give the cursor to the list adatper
		// m_cursor,
		// // Map the NAME column in the people database to...
		// m_sDispFields,
		// // The "text1" view defined in the XML template
		// m_iViewIDs);
		IntentFilter msgFilter = new IntentFilter();
		
		msgFilter.addAction("REDANT.POP.UPDATE_QUEUE_VIEW");
		msgFilter.addAction("REDANT.POP.UPLOAD_STATE_TRUE");
		msgFilter.addAction("REDANT.POP.UPLOAD_STATE_FALSE");
		msgFilter.addAction("REDANT.POP.FINISH_UPLOAD_QUEUE");
		
		registerReceiver(UploadQueueReceiver, msgFilter);
		
		m_tvalert = (TextView) findViewById(R.id.tvalert);
		m_tvalert.setSelected(true);

		
		//timer.schedule(task, 1, 300); // 参数分别是delay（多长时间后执行），duration（执行间隔）
		sendBroadcast(new Intent("REDANT.POP.QUERY_UPLOAD_STATE"));
		
	}

//	private void RefreshList()
//	{
//		// if (dbUtil.isRecordExist(m_db,
//		// "user_numberlist","type = "+m_Activityinfo.NumberType))
//		// {
//		// m_TextView.setVisibility(ListView.INVISIBLE);
//		// m_ListView.setVisibility(ListView.VISIBLE);
//		//
//		// }
//		// else
//		// {
//		// m_TextView.setVisibility(ListView.VISIBLE);
//		// m_ListView.setVisibility(ListView.INVISIBLE);
//		// }
//		hashMap.clear();
//		m_cursor.requery();
//	}

	// private void initlist()
	// {
	// m_ListView = (ListView) findViewById(android.R.id.list);
	// ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,
	// Object>>();
	// HashMap<String, Object> map = null;
	//
	// String[] strings = { "alias", "type", "name" };// Map的key集合数组
	// int[] ids = { R.id.aliasName, R.id.tv_type };// 对应布局文件的id
	// SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
	// R.layout.search_lvitem_edit, strings, ids);
	//
	// // listView1.setAdapter(simpleAdapter);//绑定适配器
	// setListAdapter(simpleAdapter);
	// }

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

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item)
//	{
//		Intent intent = new Intent();
//		switch (item.getItemId())
//		{
//		case R.id.action_custom_fields:
//			intent.setClass(this, CustomizeFieldsActivity.class);
//			intent.putExtra("user", user);
//			// intent.putExtra("password", password);
//			intent.putExtra("function_name", function_name);
//			intent.putExtra("behavior", Network.BEHAVIOR_SEARCH);
//			startActivity(intent);
//			break;
//		case R.id.action_help:
//			// Intent intent = new Intent();
//			intent.setClass(this, HelpActivity.class);
//			intent.putExtra("caller", "search");
//			// // intent.putExtra("password", password);
//			// intent.putExtra("function_name", function_name);
//			// intent.putExtra("behavior", Network.BEHAVIOR_SEARCH);
//			startActivity(intent);
//			break;
//		default:
//			break;
//		}
//		return super.onOptionsItemSelected(item);
//	}
	private final BroadcastReceiver UploadQueueReceiver	= new BroadcastReceiver()
	{

		public void onReceive(
				Context context,
				Intent intent)
		{
			String action = intent
					.getAction();
			// 如果捕捉到的action是ACTION_BATTERY_CHANGED

			if ("REDANT.POP.UPDATE_QUEUE_VIEW"
					.equals(action))
			{
				m_cursor.requery();
				

			}
			else if ("REDANT.POP.UPLOAD_STATE_FALSE"
					.equals(action))
			{
				timer.cancel();
				m_tvalert.setText("");
//				m_tvalert.setTextColor(getResources().getColor(
//						R.color.message_success));
				
				
				
			}
			else if ("REDANT.POP.UPLOAD_STATE_TRUE"
					.equals(action))
			{
				m_tvalert.setText("Uploading ...");
				timer.schedule(task, 1, 300);
				
				
			}
			else if ("REDANT.POP.FINISH_UPLOAD_QUEUE"
					.equals(action))
			{
				timer.cancel();
				m_tvalert.setText("Finish upload.");
				m_tvalert.setTextColor(getResources().getColor(
						R.color.message_success));
				
				
			}
			
		}
	};
	
}
