package com.usai.redant.photo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.usai.util.Network;
import com.usai.util.dbUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity
{
	// static final int ACTIVITY_CAMERA = 0;
	// static final int ACTIVITY_VIEW = 1;
//	static final String serverurl = "http://192.168.23.1/xampp/";
	static final String TAG = "MainActivity";
	static final int REQUEST_TAKE_PHOTO = 1;
	static final int REQUEST_SCAN_BARCODE = 2;
	static final int REQUEST_LOCKER = 3;

//	private String thumbpath = null;
	private int iwidth = 640;
	private int iheight = 480;
	private File photoFile = null;
	Bitmap thumbBitmap = null;
	// private int iPhotoCount = 0;
	public String LastFileName = "";
	private boolean m_blocked = false;
	TextView m_tvalert;
	// private String user;
	// private String password;
	String m_sName;
	String m_sPassword;
	ArrayList<String> photoList = new ArrayList<String>();
	// private SurfaceView picSV;
	// private Camera camera;
	//
	private final BroadcastReceiver m_lockedReceiver = new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_SCREEN_OFF))
			{
				Log.e("hg", "收到广播!!!=======>m_blocked=" + m_blocked);
				if (m_blocked == true)
					return;
				Intent activityintent = new Intent();
				activityintent
						.setClass(MainActivity.this, LockerActivity.class);
				startActivityForResult(activityintent, REQUEST_LOCKER);
				Log.e(TAG, "===================>start locker");
				m_blocked = true;
			}
			// if (action.equals(Intent.ACTION_USER_PRESENT)) {
			//
			// Log.e("hg", "收到广播!!!=======>m_blocked=" + m_blocked);
			// if (m_blocked == true)
			// return;
			// Intent activityintent = new Intent();
			// activityintent
			// .setClass(MainActivity.this, LockerActivity.class);
			// startActivityForResult(activityintent, REQUEST_LOCKER);
			// Log.e(TAG, "===================>start locker");
			// m_blocked = true;
			// }
		}
	};

	// @Override
	// protected void onStart() {
	// Log.i(TAG, "onStart========>m_blocked="+m_blocked);
	// // TODO Auto-generated method stub
	//
	// if (m_blocked) {
	//
	// }
	// super.onStart();
	// }
	//
	// @Override
	// protected void onStop() {
	// Log.i(TAG, "onStop========>");
	// // TODO Auto-generated method stub
	//
	// super.onStop();
	// }

	private void StartCamera()
	{
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		// Ensure that there's a camera activity to handle the intent

		if (takePictureIntent.resolveActivity(getPackageManager()) != null)
		{
			// Create the File where the photo should go
			// File photoFile = null;
			if (photoFile != null)
				photoFile = null;
			try
			{
				photoFile = createImageFile();
			}
			catch (IOException ex)
			{
				// Error occurred while creating the File
				// ...
			}
			// Continue only if the File was successfully created
			Log.i(TAG, photoFile.toString());
			if (photoFile != null)
			{
				Log.i(TAG, "start system camera====================>");
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(photoFile));
				startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.e(TAG, "=======================>MainActivity Created!");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main1);
		IntentFilter msgFilter = new IntentFilter();
		Intent intent = getIntent();

		m_sName = intent.getStringExtra("user");
		m_sPassword = intent.getStringExtra("password");

		Log.e(TAG, "user=" + m_sName + ",password=" + m_sPassword);

		msgFilter.addAction("android.intent.action.SCREEN_OFF");
		msgFilter.setPriority(2147483647);
		registerReceiver(m_lockedReceiver, msgFilter);
		Log.e(TAG, "=======================>msgFilter registed!");
		if (savedInstanceState != null)
		{
			thumbBitmap = getBitmap(savedInstanceState
					.getByteArray("thumbBitmap"));
			photoList.clear();
			// ArrayList list = (ArrayList)
			// Arrays.asList(savedInstanceState.getStringArray("arrayLabel"));
			photoList = savedInstanceState.getStringArrayList("photoList");
			// photoList = A
			// savedInstanceState.getStringArrayList("photoList");
			photoFile = (File) savedInstanceState.getSerializable("photoFile");
			// iPhotoCount = savedInstanceState.getInt("iPhotoCount");
//			thumbpath = savedInstanceState.getString("thumbpath");
			if (savedInstanceState.getString("m_sName") != null)
				m_sName = savedInstanceState.getString("m_sName");
			if (savedInstanceState.getString("m_sPassword") != null)
				m_sPassword = savedInstanceState.getString("m_sPassword");
			ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
			if (thumbBitmap != null)
			{
				thumbsImageView.setImageBitmap(thumbBitmap);
//				Log.e(TAG, "load thumbpath==" + thumbpath);
			}
			// photoFile.delete();
			TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
			countTextView.setText(photoList.size() + " Photos");

		}
		EditText edit = (EditText) findViewById(R.id.edit);

		edit.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count)
			{

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}

			@Override
			public void afterTextChanged(Editable s)
			{
				// EditText edit = (EditText) findViewById(R.id.edit);
				ImageButton ibtnUpload = (ImageButton) findViewById(R.id.ibtnOk);
				if (photoList.size() > 0 && s.length() > 0)
				{
					ibtnUpload.setVisibility(View.VISIBLE);

				}
				else
				{
					ibtnUpload.setVisibility(View.INVISIBLE);

				}
			}
		});
		// if (getRequestedOrientation() ==
		// ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
		// LinearLayout landLayout = (LinearLayout) findViewById(R.id.land);
		// landLayout.setVisibility(View.VISIBLE);
		// } else {
		// LinearLayout portLayout = (LinearLayout) findViewById(R.id.port);
		// portLayout.setVisibility(View.VISIBLE);
		// }
		ImageButton ibtnscan = (ImageButton) findViewById(R.id.ibtnScan);
		ibtnscan.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				// Intent.ACTION_PICK,
				// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				// startActivityForResult(intent, REQUEST_SCAN_BARCODE);

				intent.setClass(MainActivity.this, CaptureActivity.class);
				startActivityForResult(intent, REQUEST_SCAN_BARCODE);
			}
		});

		ImageButton captureButton = (ImageButton) findViewById(R.id.ibtnCapture);
		captureButton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				StartCamera();
			}
		});
		ImageButton uploadButton = (ImageButton) findViewById(R.id.ibtnOk);
		uploadButton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				new UploadTask().execute((Void) null);
			}
		});

		m_tvalert = (TextView) findViewById(R.id.tvalert);
		m_tvalert.setSelected(true);

	}

	@Override
	protected void onDestroy()
	{
		// TODO Auto-generated method stub
		Log.e(TAG, "=======================>MainActivity Destroyed!");
		unregisterReceiver(m_lockedReceiver);
		Log.e(TAG, "=======================>msgFilter unregisted!");
		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.main, menu);
		return true;
	}

	private File createImageFile() throws IOException
	{
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = "JPEG_" + timeStamp + "_";
		File storageDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
		// Log.d(TAG, "DIR:" + storageDir);
		LastFileName = storageDir + imageFileName + ".jpg";
		Log.d(TAG, "File:" + LastFileName);
		File image = File.createTempFile(imageFileName, /* prefix */
				".jpg", /* suffix */
				storageDir /* directory */
		);

		// Save a file: path for use with ACTION_VIEW intents
		// mCurrentPhotoPath = "file:" + image.getAbsolutePath();
		return image;
	}

//	public static void savePic(Bitmap b, String strFileName)
//	{
//		FileOutputStream fos = null;
//		try
//		{
//			fos = new FileOutputStream(strFileName);
//			if (null != fos)
//			{
//
//				b.compress(Bitmap.CompressFormat.PNG, 90, fos);
//				fos.flush();
//				fos.close();
//			}
//		}
//		catch (FileNotFoundException e)
//		{
//			e.printStackTrace();
//		}
//		catch (IOException e)
//		{
//			e.printStackTrace();
//		}
//	}

	boolean createDir(String path)
	{
		Log.i(TAG, "readFile:createDir=" + path);
		boolean ret = false;
		try
		{
			File file = new File(path);
			if (!file.exists())
				file.mkdirs();
			if (!file.isDirectory())
			{
				ret = file.mkdirs();
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, e.toString());
		}
		return ret;
	}

	void updateUploadButton()
	{
		EditText edit = (EditText) findViewById(R.id.edit);
		ImageButton ibtnUpload = (ImageButton) findViewById(R.id.ibtnOk);
		if (photoList.size() > 0 && edit.getText().length() > 0)
		{
			ibtnUpload.setVisibility(View.VISIBLE);

		}
		else
		{
			ibtnUpload.setVisibility(View.INVISIBLE);

		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		if (requestCode == REQUEST_TAKE_PHOTO)
			// 处理照相机拍照的图片
			if (resultCode == Activity.RESULT_OK) // 继续拍照

			{
				// Log.e(TAG, msg)
				// Bundle bundle = data.getExtras();
				// if(thumbBitmap!=null)
				// thumbBitmap=null;
				// thumbBitmap = (Bitmap) bundle.get("data");
				// // 获取相机返回的数据，并转换为Bitmap图片格式
				// Bitmap thumbBitmap = BitmapFactory.decodeFile(photoFile
				// .toString());

				// CreateThumb(photoFile);
				Log.e(TAG, photoFile.toString());
				photoList.add(photoFile.toString());

				// Bitmap.createScaledBitmap(
				// thumbBitmap, thumbsImageView.getWidth(),
				// thumbsImageView.getHeight(), false));
				// Log.i(TAG, "thumb size" + thumbBitmap.getHeight() + "x"
				// + thumbBitmap.getWidth());
//				thumbpath = photoFile.toString();
//				Log.e(TAG, "get thumbpath==" + thumbpath);
				StartCamera();
				// iPhotoCount++;
				super.onActivityResult(requestCode, resultCode, data);

			}
			else
			{
				// 退出拍照
				// File emptyFile = new File(LastFileName);
				// boolean b=emptyFile.delete();
//				Log.i(TAG, "lastpicPath: " + thumbpath);
				ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
				// thumbBitmap=getImageThumbnail(thumbpath, iwidth,iheight);
				if(photoList.size()>0)
				{
					thumbBitmap = ThumbnailUtils.extractThumbnail(
							BitmapFactory.decodeFile(photoList.get(photoList.size()-1)), iwidth, iheight);
					if (thumbBitmap != null)
						thumbsImageView.setImageBitmap(thumbBitmap);
				}
//				thumbBitmap = ThumbnailUtils.extractThumbnail(
//						BitmapFactory.decodeFile(thumbpath), iwidth, iheight);
				// saveMyBitmap("thumbtest",thumbBitmap);
//				if (thumbBitmap != null)
//					thumbsImageView.setImageBitmap(thumbBitmap);
				photoFile.delete();
				TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
				countTextView.setText(photoList.size() + " Photos");
				// ImageButton ibtnUpload = (ImageButton)
				// findViewById(R.id.ibtnOk);
				updateUploadButton();

			}

		else
			if (requestCode == REQUEST_LOCKER)
			{
				if (resultCode == Activity.RESULT_OK)
					m_blocked = false;
			}
			else
				if (requestCode == REQUEST_SCAN_BARCODE)
				{
					if (resultCode == Activity.RESULT_OK)
					{
						Bundle bundle = data.getExtras();
						String pid = bundle.getString("pid");
						Log.e(TAG, "REQUEST_SCAN_BARCODE==========>pid="
								+ bundle.getString("pid"));
						EditText edit = (EditText) findViewById(R.id.edit);
						edit.setText(pid);
						// updateUploadButton();
					}
				}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveMyBitmap(String bitName, Bitmap mBitmap)
	{
		File f = new File("/sdcard/" + bitName + ".png");
		try
		{
			f.createNewFile();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			// DebugMessage.put("在保存图片时出错：" + e.toString());
		}
		FileOutputStream fOut = null;
		try
		{
			fOut = new FileOutputStream(f);
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try
		{
			fOut.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		try
		{
			fOut.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// TODO Auto-generated method stub
		switch (item.getItemId())
		{
		case R.id.action_orientation:
			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			else
			{
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			}
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		if (photoFile != null)
			outState.putSerializable("photoFile", photoFile);

		if (thumbBitmap != null)
			outState.putByteArray("thumbBitmap", getBytes(thumbBitmap));// ("thumbBitmap",
																		// (Object)thumbBitmap);
//		outState.putString("thumbpath", thumbpath);
		outState.putString("m_sName", m_sName);
		outState.putString("m_sPassword", m_sPassword);

		outState.putStringArrayList("photoList", photoList);
//		Log.e(TAG, "save thumbpath==" + thumbpath);
		outState.putInt("iPhotoCount", photoList.size());
	}

	public static byte[] getBytes(Bitmap bitmap)
	{
		// 实例化字节数组输出流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);// 压缩位图
		return baos.toByteArray();// 创建分配字节数组
	}

	public static Bitmap getBitmap(byte[] data)
	{
		if (data == null)
			return null;
		return BitmapFactory.decodeByteArray(data, 0, data.length);// 从字节数组解码位图
	}

	private void clearfornew()
	{
		photoList.clear();
		EditText edit = (EditText) findViewById(R.id.edit);
		edit.setText("");
		updateUploadButton();
		ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
		thumbsImageView.setImageResource(R.drawable.no_pic);	
		thumbBitmap=null;
		TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
		countTextView.setText("no photo");

	}
	public class UploadTask extends AsyncTask<Void, Void, Boolean>
	{
		String err_msg="";
		@Override
		protected Boolean doInBackground(Void... params)
		{
			boolean bret=true;


			SQLiteDatabase db = dbUtil.OpenDB(MainActivity.this, null, true);
			EditText edit = (EditText) findViewById(R.id.edit);
			String pid = edit.getText().toString();

			if (Network.NetworkIsAvailable(MainActivity.this))
			{
				int verifyresult = Network.VerifyUser(m_sName, m_sPassword);
				if (verifyresult == Network.RESULT_TRUE)
				{
					/* user is authorized */
					for (int i = 0; i < photoList.size(); i++)
					{
						int uploadresult = Network.UploadFile(photoList.get(i),
								m_sName, m_sPassword, pid);
						if (uploadresult != Network.RESULT_TRUE)
						{
							/*
							 * upload failed write to local db upload when
							 * connect to network next time;
							 */

							/*
							 * serious error occur must notify user
							 * immediately
							 */
							if (uploadresult == Network.RESULT_LOCALFILE_ERROR)
								err_msg+="Warring! Local picture file not found!      ";
							if( uploadresult == Network.RESULT_USERAUTH_ERROR)
								err_msg+="Warring! Authorize check failed when uploading photos!      ";

							ContentValues cv = new ContentValues();
							cv.put("picker", m_sName);
							cv.put("err_code", uploadresult);
							cv.put("pid", pid);
							cv.put("local_path", photoList.get(i));
							db.insert("pics", null, cv);
							bret=false;
						}
						else
						{
							/* upload success delete file */
							File file = new File(photoList.get(i));
							file.delete();
						}

					}

				}
				else
					if (verifyresult == Network.RESULT_FALSE)
					{
						/*
						 * user is not authorized serious error occur must
						 * notify user
						 */
						Log.e(TAG, "notification====================>");
						// String text=m_tvalert.getText().toString();
						err_msg+="Warring! Authorize check failed when uploading photos!";
						bret=false;
						for (int i = 0; i < photoList.size(); i++)
						{
							ContentValues cv = new ContentValues();
							cv.put("picker", m_sName);
							cv.put("err_code", Network.RESULT_USERAUTH_ERROR);
							cv.put("pid", pid);
							cv.put("local_path", photoList.get(i));
							db.insert("pics", null, cv);
						}

					}
					else
					{
						/* an error occur */
						for (int i = 0; i < photoList.size(); i++)
						{
							ContentValues cv = new ContentValues();
							cv.put("picker", m_sName);
							cv.put("err_code", Network.RESULT_NET_ERROR);
							cv.put("pid", pid);
							cv.put("local_path", photoList.get(i));
							db.insert("pics", null, cv);
						}
						bret = false;
					}
			}
			else
			{
				/*
				 * net work is not available store into local DB it will auto
				 * upload when connect to network next time;
				 */

				for (int i = 0; i < photoList.size(); i++)
				{
					ContentValues cv = new ContentValues();
					cv.put("picker", m_sName);
					cv.put("err_code", Network.RESULT_NET_ERROR);
					cv.put("pid", pid);
					cv.put("local_path", photoList.get(i));
					db.insert("pics", null, cv);
				}
				bret=false;
				// m_tvalert.setText("Upload failed when uploading photos!");

			}

			dbUtil.CloseDB(db);
			return bret;
		}

		@Override
		protected void onPostExecute(final Boolean success)
		{
			if(success)
			{
				m_tvalert.setTextColor(getResources().getColor(R.color.message_success));
				m_tvalert.setText("Upload successed!");
			}
			else
			{
				m_tvalert.setTextColor(getResources().getColor(R.color.message_fail));
				m_tvalert.setText(err_msg);
			}
			
			clearfornew();
			// mAuthTask = null;
			// showProgress(false);
			//
			// if (success) {
			//
			// // SharedPreferences.Editor editor = RunOnce.edit();
			// // editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
			// false);
			// // // Don't forget to commit your edits!!!
			// // editor.commit();
			// Intent intent = new Intent();
			// intent.setClass(LoginActivity.this, MainActivity.class);
			// startActivity(intent);
			// finish();
			// } else {
			// m_etPassword
			// .setError(getString(R.string.error_incorrect_password));
			// m_etPassword.requestFocus();
			// }
		}

		@Override
		protected void onCancelled()
		{
			// mAuthTask = null;
			// showProgress(false);
		}
	}

}
