package com.usai.redant.raimage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.usai.redant.raimage.Model.ManufactureListActivity;
import com.usai.redant.raimage.PhotoList.PhotoGridActivity;
import com.usai.util.AES;
import com.usai.util.MD5;
import com.usai.util.Network;
import com.usai.util.RAUtil;
import com.usai.util.dbgUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class MainActivity extends AppCompatActivity
{


    protected String mode=null;
    protected String name=null;
    private VerifyCodeTask verifytask=null;
    private QueryManufacturer qmtask=null;
    private JSONArray manufacture_arr=null;
    private AlertDialog qmdialog =null;
    private AlertDialog vfdialog =null;
    public void verifyandupload(Bundle params)
    {
        if (verifytask != null)
        {
            return;
        }

        String title = "Verifying "+name;

//        if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//            title = "Verifying Model";
//        }

        vfdialog=new AlertDialog.Builder(MainActivity.this)
                .setTitle(title)
                .setMessage("Please Wait")

                .show();

        verifytask = new VerifyCodeTask();
        verifytask.execute(params);

    }
    public void querymanufacturer(Bundle params)
    {
        if (qmtask != null)
        {
            return;
        }



        qmdialog=new AlertDialog.Builder(MainActivity.this)
                .setTitle("Searching manufacturer")
                .setMessage("Please Wait")

                .show();
        qmtask = new QueryManufacturer();
        qmtask.execute(params);

    }
    public class QueryManufacturer extends AsyncTask<Bundle, Void, Boolean>
    {

        JSONObject json	= null;

        // int netconnect;

        @Override
        protected Boolean doInBackground(Bundle... params)
        {
            json = Network.Query_Manufacturer(params[0]);
            try {
                if (json.getInt("result") == Network.RESULT_TRUE)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(final Boolean success)
        {

            Log.i("onPostExecute", "entry");
            qmtask = null;
            qmdialog.hide();
//            showProgress(false);

            if (success)
            {


                try {
                    manufacture_arr=json.getJSONArray("manufacturer");
                    if(manufacture_arr.length()==1) {
                        String manufacture = manufacture_arr.getString(0);
                        setManufacture(manufacture);
                    }
                    else
                    {
                        if(manufacture_arr.length()==0)
                    {
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                "No manufacturer found, wrong model?",
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();


                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage("No manufacturer found, wrong model?")
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();

                    }
                        setManufacture("");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


                //验证成功


//                Intent intent = new Intent("REDANT.RAImage.ADD_TASK");
//
//                ArrayList<Bundle> taskArr = new ArrayList<Bundle>();
//                String name = "POP";
//
////					if(MainActivity.this instanceof ModelActivity)
////						name=name = "Model";
//                if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//                    name = "Model";
//                }
//                for (String path : photoList) {
//                    Bundle task = new Bundle();
//
//                    task.putString("path",path);
//                    task.putString("file",RAUtil.lastPathComponent(path));
//                    task.putString("url",RedAntApplication.active_address);
//
//                    String md5 = MD5.md5sum(path);
//                    String encryptUser = AES.encrypt("usai",RedAntApplication.user);
//                    String encryptPwd = AES.encrypt("usai",RedAntApplication.password);
//
//                    Bundle params = new Bundle();
//                    params.putString("user",encryptUser);
//                    params.putString("password",encryptPwd);
//                    params.putString("mode",name);
//                    params.putString("barcode",pidval.getText().toString());
//                    params.putString("_operate","upload");
//                    params.putString("platform","android");
//                    params.putString("md5",md5);
//
//
//                    if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//
//                        if (!TextUtils.isEmpty(manufacture)) {
//                            params.putString("manufacturer",manufacture);
//                        }
//                        if (!TextUtils.isEmpty(noteTextView.getText().toString())) {
//                            params.putString("note",noteTextView.getText().toString());
//                        }
//                    }
//
//                    task.putBundle("params",params);
//
//                    taskArr.add(task);
//                }
//
//                intent.putParcelableArrayListExtra("tasks",taskArr);
//
//                sendBroadcast(intent);
//                clearfornew();
            }
            else
            {
                int result = 0;
                try {
                    result = json.getInt("result");
                } catch (Exception e) {
                    e.printStackTrace();
                    result = Network.RESULT_NET_ERROR;

                }
                switch (result)
                {
                    case 0:
                    {
                        // model , piid not exist


                        String msg = "User / password does not match.";

//                        if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//                            msg = "Model does not exist.";
//                        }
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                msg,
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        break;

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage(msg)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();
                        break;
                    }
//                    case 1:
//                    {
//                        //model / manufacturer not match
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                "Model/Manufacturer does not match.",
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        break;
//                    }
                    default:
                    {
//                        // net error.
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                "Can not get manufacturer information.",
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        return;

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage("Can not get manufacturer information.")
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();
                        return;
                    }

                }

            }
        }

        @Override
        protected void onCancelled()
        {
            verifytask = null;

        }
    }
    public class VerifyCodeTask extends AsyncTask<Bundle, Void, Boolean>
    {

        JSONObject json	= null;

        // int netconnect;

        @Override
        protected Boolean doInBackground(Bundle... params)
        {
            json = Network.Verify_Code(params[0]);
            try {
                if (json.getInt("result") == Network.RESULT_TRUE)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(final Boolean success)
        {
            Log.i("onPostExecute", "entry");
            verifytask = null;
//            showProgress(false);

            vfdialog.hide();

            if (success)
            {
               //验证成功


                Intent intent = new Intent("REDANT.RAImage.ADD_TASK");

                ArrayList<Bundle> taskArr = new ArrayList<Bundle>();
//                String name = "POP";
//
////					if(MainActivity.this instanceof ModelActivity)
////						name=name = "Model";
//                if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//                    name = "Model";
//                }
                for (String path : photoList) {
                    Bundle task = new Bundle();

                    task.putString("path",path);
                    task.putString("file",RAUtil.lastPathComponent(path));
                    task.putString("url",RedAntApplication.active_address);

                    String md5 = MD5.md5sum(path);
                    String encryptUser = AES.encrypt("usai",RedAntApplication.user);
                    String encryptPwd = AES.encrypt("usai",RedAntApplication.password);

                    Bundle params = new Bundle();
                    params.putString("user",encryptUser);
                    params.putString("password",encryptPwd);
                    params.putString("mode",mode);
                    params.putString("barcode",pidval.getText().toString());
                    params.putString("_operate","upload");
                    params.putString("platform","android");
                    params.putString("md5",md5);


                    if (mode.equals("Model")) {

                        if (!TextUtils.isEmpty(manufacture)) {
                            params.putString("manufacturer",manufacture);
                        }
                        if (!TextUtils.isEmpty(noteTextView.getText().toString())) {
                            params.putString("note",noteTextView.getText().toString());
                        }
                    }

                    task.putBundle("params",params);

                    taskArr.add(task);
                }

                intent.putParcelableArrayListExtra("tasks",taskArr);

                sendBroadcast(intent);
                clearfornew();
            }
            else
            {
                int result = 0;
                try {
                    result = json.getInt("result");
                } catch (Exception e) {
                    e.printStackTrace();
                    result = Network.RESULT_NET_ERROR;

                }
                switch (result)
                {
                    case 0:
                    {
                        // model , piid not exist


                        String msg = name+" does not exist";

//                        if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//                            msg = "Model does not exist.";
//                        }
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                msg,
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        break;


                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage(msg)
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();
                        break;



                    }
                    case 1:
                    {
                        //model / manufacturer not match
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                "Model/Manufacturer does not match.",
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        break;


                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage("Model/Manufacturer does not match.")
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();
                        break;
                    }
                    default:
                    {
                        // net error.
//                        Toast toast = Toast.makeText(getApplicationContext(),
//                                "can not verify input information.",
//                                Toast.LENGTH_LONG);
//                        toast.setGravity(Gravity.CENTER, 0, 0);
//                        toast.show();
//                        return;

//                        new AlertDialog.Builder(MainActivity.this)
//                                .setTitle("Warning")
//                                .setMessage("can not verify input information.")
//                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                })
//                                .show();


                        			new AlertDialog.Builder(MainActivity.this)
					.setTitle("Warning")
					.setMessage("Can not verify input information, server is not reachable for now, add upload task anyway?")
					.setPositiveButton("Yes", new DialogInterface.OnClickListener()
                    {
						@Override
						public void onClick(DialogInterface dialog, int which)             {


                            Intent intent = new Intent("REDANT.RAImage.ADD_TASK");

                            ArrayList<Bundle> taskArr = new ArrayList<Bundle>();

                            for (String path : photoList) {
                                Bundle task = new Bundle();

                                task.putString("path",path);
                                task.putString("file",RAUtil.lastPathComponent(path));
                                task.putString("url",RedAntApplication.active_address);

                                String md5 = MD5.md5sum(path);
                                String encryptUser = AES.encrypt("usai",RedAntApplication.user);
                                String encryptPwd = AES.encrypt("usai",RedAntApplication.password);

                                Bundle params = new Bundle();
                                params.putString("user",encryptUser);
                                params.putString("password",encryptPwd);
                                params.putString("mode",mode);
                                params.putString("barcode",pidval.getText().toString());
                                params.putString("_operate","upload");
                                params.putString("platform","android");
                                params.putString("md5",md5);


                                if (mode.equals("Model")) {

                                    if (!TextUtils.isEmpty(manufacture)) {
                                        params.putString("manufacturer",manufacture);
                                    }
                                    if (!TextUtils.isEmpty(noteTextView.getText().toString())) {
                                        params.putString("note",noteTextView.getText().toString());
                                    }
                                }

                                task.putBundle("params",params);

                                taskArr.add(task);
                            }

                            intent.putParcelableArrayListExtra("tasks",taskArr);

                            sendBroadcast(intent);
                            clearfornew();
                        }

                    })
					.setNegativeButton("No", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					})
					.show();
                        return;

                    }

                }

            }
        }

        @Override
        protected void onCancelled()
        {
            verifytask = null;

        }
    }

    static final boolean newVersion = true;
	// 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_PREVIEW			= 4;
	static final int	REQUEST_SCAN_BARCODE	= 2;
	static final int	REQUEST_LOCKER			= 3;
	static final int 	REQUEST_MANUFACTURE 	= 5;
	// HashMap<String, String> hashMap = new HashMap<String, String>();

	// ArrayList<String> pic_file = new ArrayList<String>();
	// ArrayList<bitmap>
	// ArrayList<>
	// 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>();

	// @Override
	// protected void onResume()
	// {
	// //sendBroadcast(new Intent("REDANT.POP.REQUEST_LOCATION_CHANGED"));
	// super.onResume();
	// }

	/** RA Image */
	protected ImageView thumbsImageView;
	protected TextView countTextView;
	protected EditText pidval;
	protected EditText noteTextView;
	protected ImageButton ibtnscan;
	protected ImageButton captureButton;
	protected ImageButton uploadButton;
	protected Button manufactureBtn;
    protected  Button btnType;
	private String manufacture;

	void setManufacture(String value) {
        if(manufactureBtn==null)
            return;
		manufacture = value;
		if (TextUtils.isEmpty(value)) {
			manufactureBtn.setText("Select Manufacturer");
		} else  {
			manufactureBtn.setText(value);
		}
	}

	public void showWarning(String msg) {
		if (TextUtils.isEmpty(msg)) {
			msg = "Warning Message";
		}
		new AlertDialog.Builder(MainActivity.this)
				.setTitle("Warning")
				.setMessage(msg)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				})
				.show();
	}

//	public boolean checkCameraPermission() {
//		int permission = ContextCompat.checkSelfPermission(MainActivity.this, "android.permission.CAMERA");
//		if (permission == PackageManager.PERMISSION_DENIED) {
//
//			new AlertDialog.Builder(this)
//					.setTitle("Warning")
//					.setMessage("RA Image need camera permission")
//					.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//							intent.setData(Uri.parse("package:" + getPackageName()));
//							startActivity(intent);
//						}
//					})
//					.setNegativeButton("No", new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//							finish();
//						}
//					})
//					.show();
//
//			return false;
//		}
//		return true;
//	}

	protected void initView() {
		thumbsImageView = (ImageView)findViewById(R.id.photo_iv);
		countTextView = (TextView)findViewById(R.id.photo_count_lb);
		pidval = (EditText)findViewById(R.id.barcode_et);

        if (mode.equals("Model")) { // model

            pidval.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    // 输入的内容变化的监听
//                Log.e("输入过程中执行该方法", "文字变化");
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {
                    // 输入前的监听
//                Log.e("输入前确认执行该方法", "开始输入");

                }

                @Override
                public void afterTextChanged(Editable s) {
                    // 输入后的监听

                    String model = s.toString();
                    if(TextUtils.isEmpty(model))
                        return;
                    Log.e("输入结束执行该方法", "输入结束"+ s.toString());

                    String encryptUser = AES.encrypt("usai",RedAntApplication.user);
                    String encryptPwd = AES.encrypt("usai",RedAntApplication.password);

                    Bundle params = new Bundle();
                    params.putString("user",encryptUser);
                    params.putString("password",encryptPwd);
                    params.putString("barcode",model);
                    params.putString("type","model");
                    params.putString("_operate","handset_get_manufacturer");
                    params.putString("platform","android");


                    querymanufacturer(params);

                }
            });
        }


		noteTextView = (EditText)findViewById(R.id.note_et);
		ibtnscan = (ImageButton)findViewById(R.id.scan_btn);
		captureButton = (ImageButton)findViewById(R.id.camera_btn);
		uploadButton = (ImageButton)findViewById(R.id.upload_btn);
		manufactureBtn = (Button)findViewById(R.id.manufacture_btn);

        btnType = (Button)findViewById(R.id.btn_type);
        btnType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText edit = new EditText(MainActivity.this);
                String msg = "Please enter "+name;
//                if (MainActivity.this.getClass().equals(ModelActivity.class)) { // model
//
//
//                }
//                else
//                    if (MainActivity.this.getClass().equals(PopActivity.class))
//                {
//                    edit.setInputType(InputType.TYPE_CLASS_NUMBER);
//                    msg = "Please enter PIID code";
//                }

                if(mode.equals("POP")||mode.equals("Returns"))
                {
                    edit.setInputType(InputType.TYPE_CLASS_NUMBER);
                }

                edit.setSingleLine(true);

				new AlertDialog.Builder(MainActivity.this)
						.setIconAttribute(android.R.attr.alertDialogIcon)
						.setTitle(msg)
						.setView(edit)
						.setPositiveButton(android.R.string.ok,
								new DialogInterface.OnClickListener()
								{
									public void onClick(DialogInterface dialog,
											int whichButton)
									{
										String pid = ((EditText) edit)
												.getText().toString();
//										TextView pidval = (TextView) findViewById(R.id.pidval);
										pidval.setText(pid);
										updateUploadButton();

										/* User clicked OK so do some stuff */
									}
								})
						.setNegativeButton(android.R.string.cancel,
								new DialogInterface.OnClickListener()
								{
									public void onClick(DialogInterface dialog,
											int whichButton)
									{
										updateUploadButton();
										/* User clicked cancel so do some stuff */
									}
								}).create().show();
            }
        });

        /***/
		thumbsImageView.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				if (photoList.size() < 1) {
					StartCamera();
					return;
				}


//				Intent intent = new Intent(MainActivity.this,
//						PhotoPreviewActivity.class);
//				intent.putExtra("pic_list", (Serializable) photoList);
//				startActivityForResult(intent, REQUEST_PREVIEW);

//				Intent intent = new Intent(MainActivity.this,
//						PhotoListActivity.class);
//				intent.putExtra("pic_list", (Serializable) photoList);
//				startActivityForResult(intent, REQUEST_PREVIEW);

                Intent intent = new Intent(MainActivity.this, PhotoGridActivity.class);
                intent.putExtra("pic_list", (Serializable) photoList);
                startActivityForResult(intent, REQUEST_PREVIEW);

			}
		});

        ibtnscan.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                Log.d(TAG, "==============>Click Scan button");

//®

                Intent intent = new Intent();

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

        captureButton.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {

                StartCamera();
            }
        });
        uploadButton.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
				if (TextUtils.isEmpty(pidval.getText().toString())) {
					String barcode_title = name;//"PIID";
//					if (MainActivity.this.getClass().equals(ModelActivity.class)) { // model
//						barcode_title = "Model";
//					}
					showWarning(barcode_title + " can not be blank!");
					return;
				}
                if (name.equals("Model"))//(MainActivity.this.getClass().equals(ModelActivity.class))
                {
                    if (TextUtils.isEmpty(manufacture)) {
                        showWarning("manufacture can not be blank!");
                        return;
                    }
                }



				if (photoList.size() < 1) {
					showWarning("You must take at least one photo");
					return;
				}



		//		boolean canstart = true;

				ConnectivityManager connManager = (ConnectivityManager) RedAntApplication.getInstance()
						.getSystemService(Context.CONNECTIVITY_SERVICE);

				NetworkInfo networkInfo = connManager
						.getActiveNetworkInfo();
				if (networkInfo == null)
				{
					dbgUtil.Logd(
							"Current Network info",
							"can not get Active NetworkInfo!");
//					canstart = false;
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("Warning")
                            .setMessage("No available network, new task will not start, you must start it manually.")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            })
                            .show();
				}
				else
				{
					NetworkInfo.State netState = networkInfo
							.getState();
					if (netState != NetworkInfo.State.CONNECTED)
					{
						dbgUtil.Logd(
								"Current Network info",
								"not Connected!State="
										+ netState);
//						canstart = false;

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Warning")
                                .setMessage("No network connection, new task will not start, you must start it manually.")
                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .show();

					}
					else
                    {
                        int iconntype = -1;
                        iconntype = networkInfo
                                .getType();

                        SharedPreferences pref = RedAntApplication
                                .getInstance()
                                .getSharedPreferences(
                                        "UploadManager",
                                        0);
                        boolean
                                wifi_only
                                =pref.getBoolean("wifi_only",
                                false);
                        if(wifi_only == true
                                && iconntype !=
                                ConnectivityManager.TYPE_WIFI
                                && iconntype !=
                                9/* earthnet */)
                        {
//						canstart = false;


                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("Warning")
                                    .setMessage("You have setup upload via WIFI only, new task will not start, you must start it manually.")
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .show();



                        }
                    }

				}
//				if(!canstart)
//				{
//

////                    new AlertDialog.Builder(MainActivity.this)
////                            .setTitle("Warning")
////                            .setMessage("App is set to upload via WIFI only. Please change your setting or try upload later.")
////                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
////                                @Override
////                                public void onClick(DialogInterface dialog, int which) {
////
////                                }
////                            })
////                            .show();
////                    return;
//
//				}
				try {

//                    String name = "POP";
//
////					if(MainActivity.this instanceof ModelActivity)
////						name=name = "Model";
//                    if (MainActivity.this.getClass().equals(ModelActivity.class)) {
//                        name = "Model";
//                    }
                    String encryptUser = AES.encrypt("usai",RedAntApplication.user);
                    String encryptPwd = AES.encrypt("usai",RedAntApplication.password);




                    Bundle params = new Bundle();
                    params.putString("user",encryptUser);
                    params.putString("password",encryptPwd);
                    params.putString("mode",mode);
                    params.putString("barcode",pidval.getText().toString());
                    params.putString("_operate","upload");
                    params.putString("platform","android");

                    if (mode.equals("Model")) {

                        if (!TextUtils.isEmpty(manufacture)) {
                            params.putString("manufacturer",manufacture);
                        }

                    }

                    verifyandupload(params);


				} catch (Exception e) {
					e.printStackTrace();
				}
				return;

            }
        });

		/**Model*/
		if (mode.equals("Model")) {
			if (manufactureBtn != null) {
				manufactureBtn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(MainActivity.this, ManufactureListActivity.class);

                        JSONArray manufactureArr = manufacture_arr;

                        if(manufactureArr==null/*||manufactureArr.length()==0*/)
                        {

                            try {
                                JSONArray modeArr = RedAntApplication.server_info.getJSONArray("modellist");
                                for (int i = 0;i < modeArr.length(); i++) {
                                    JSONObject obj = modeArr.getJSONObject(i);
                                    String name = obj.getString("name");
                                    if (name.equals("Model")) {
                                        manufactureArr = obj.getJSONArray("manifacturer");

                                    }
                                    break;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        ArrayList<String> mlist = new ArrayList<String>();
                        for (int j = 0; j < manufactureArr.length(); j++) {
                            String manufacture = null;
                            try {
                                manufacture = manufactureArr.getString(j);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mlist.add(manufacture);
                        }

                        intent.putStringArrayListExtra("mlist",mlist);
						startActivityForResult(intent,REQUEST_MANUFACTURE);
					}
				});
			}
		}



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

        sendBroadcast(new Intent("REDANT.POP.MODIFY_QUEUE"));
        updateUploadButton();

	}

	protected void recovery(Bundle savedInstanceState) {
        if (savedInstanceState != null)
        {
//			Bitmap savedBitmap = getBitmap(savedInstanceState
//					.getByteArray("thumbBitmap"));
			ArrayList<String>	savedPhotoList =  savedInstanceState.getStringArrayList("photoList");
            String savedPiid = savedInstanceState.getString("PIID");
			String savedNote = savedInstanceState.getString("Note");
			File savedPhotoFile = (File) savedInstanceState.getSerializable("photoFile");
			String manufacture = savedInstanceState.getString("manufacture");

//			if (savedBitmap != null) {
//				thumbBitmap = savedBitmap;
//			}




            if (savedPhotoList != null) {
				photoList = savedPhotoList;

                if(photoList.size()>=1)
                    thumbBitmap =  BitmapFactory.decodeFile(photoList.get(photoList.size() - 1));
                if(thumbBitmap!=null)
                    thumbsImageView.setImageBitmap(thumbBitmap);
                else
                    thumbsImageView.setImageResource(R.drawable.no_pic);
                Log.e(TAG, "recovery: photolist"+photoList.size());
            }
            else

            {
                thumbsImageView.setImageResource(R.drawable.no_pic);
            }



            if (!TextUtils.isEmpty(savedPiid)) {
				pidval.setText(savedPiid);
				pidval.setSelection(savedPiid.length());
			}
            if (savedPhotoFile != null) {
				photoFile = savedPhotoFile;
			}
            if (thumbBitmap != null)
            {
                thumbsImageView.setImageBitmap(thumbBitmap);
            }
            countTextView.setText(photoList.size() + " Photos");

			/** Model */
			if (mode.equals("Model")) {
				if (!TextUtils.isEmpty(savedNote)) {
					noteTextView.setText(savedNote);
					noteTextView.setSelection(savedNote.length());
				}
				setManufacture(manufacture);
			}

        }
    }

    private File compressImageFile(File imgFile) {


        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());

        String barcode_title = name;//"PIID";
//        if (MainActivity.this.getClass().equals(ModelActivity.class)) { // model
//            barcode_title = "Model";
//        }
        String imageFileName = barcode_title + timeStamp +".jpg";


        File routedFile = RAUtil.routeBitmap(imgFile,imageFileName);

		SharedPreferences preferences = RedAntApplication.getInstance().getSharedPreferences("UploadManager", 0);
		boolean auto_compress = preferences.getBoolean("compress",true);
		if (auto_compress) { // 压缩

			String path = routedFile.getPath();

//			Bitmap source = BitmapFactory.decodeFile(path);

			Bitmap source = null;
			try {
				FileInputStream stream = new FileInputStream(routedFile);
				source = BitmapFactory.decodeStream(stream);
			} catch (FileNotFoundException e) {
				return routedFile;
			}

			if (source == null) {
				return routedFile;
			}

			int originWidth = source.getWidth();
			int originHeight = source.getHeight();

			int width = originWidth, height = originHeight;

			if (originHeight > 1024 || originWidth > 1024)
			{
				if (originWidth > originHeight)
				{
					width = 1024;
					height = originHeight * 1024 / originWidth;

				}
				else
				{

					height = 1024;
					width = originWidth * 1024 / originHeight;

				}
			}
			Bitmap scaled = Bitmap.createScaledBitmap(source, width, height, true);



			String scalePath = path.replace(".jpg", "_scaled.jpg");
			File scaleFile = new File(scalePath);
			try {

				FileOutputStream outputStream = new FileOutputStream(scaleFile);
				scaled.compress(Bitmap.CompressFormat.JPEG, 95, outputStream);

				outputStream.flush();
				outputStream.close();

                String rotedpath = routedFile.getAbsolutePath();
                routedFile.delete();
                RAUtil.updateGallery(rotedpath);
//				scaleFile.renameTo(new File(path));
				return scaleFile;

			} catch (IOException e) {
				e.printStackTrace();
				return routedFile;
			}


		}
		else
        {
            return routedFile;
        }


	}

	private void StartCamera()
	{

//		if (!RAUtil.checkPermission(this,"android.permission.CAMERA")) {
//			return;
//		}

		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,
                        getImageContentUri(this,photoFile)/*Uri.fromFile(photoFile)*/);
				startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
			}
		}
	}

    private Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID },
                MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);

        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }




	@Override
	protected void onResume()
	{
		sendBroadcast(new Intent("REDANT.POP.GPS_ON"));
		super.onResume();

	}

	@Override
	protected void onPause()
	{
		sendBroadcast(new Intent("REDANT.POP.GPS_OFF"));
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		Log.d(TAG, "=======================>MainActivity Created!");
		super.onCreate(savedInstanceState);




        mode = getIntent().getStringExtra("mode");
        name = getIntent().getStringExtra("name");

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

		Log.d(TAG, "user=" + RedAntApplication.user + ",password="
				+ RedAntApplication.password);
		IntentFilter msgFilter = new IntentFilter();
		Intent intent = getIntent();

		msgFilter.addAction("REDANT.RAImage.UPLOAD_COMPLETE");

		msgFilter.setPriority(2147483647);
		registerReceiver(MainActivityReceiver, msgFilter);
		Log.d(TAG, "=======================>msgFilter registed!");

        if (newVersion) {
            return;
        }

	}

	@Override
	protected void onDestroy()
	{

		Log.d(TAG, "=======================>MainActivity Destroyed!");
		unregisterReceiver(MainActivityReceiver);
		Log.d(TAG, "=======================>msgFilter unregisted!");
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		if (newVersion) {
			getMenuInflater().inflate(R.menu.mode_menu, menu);
			return true;
		}
		// 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 = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/redant/pop/temp/");

		File dir1 = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/redant");
		File dir2 = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/redant/pop");
		File dir3 = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/redant/pop/temp");

		
		if (!dir1.exists())
		{
			boolean b = dir1.mkdir();
		}
		if (!dir2.exists())
		{
			boolean b = dir2.mkdir();
		}
		if (!dir3.exists())
		{
			boolean b = dir3.mkdir();
		}
		// 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 */
		);

        Log.d(TAG, "File:" + image.getAbsolutePath());
//        RAUtil.updateGallery(LastFileName);

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

	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.d(TAG, e.toString());
		}
		return ret;
	}

	void updateUploadButton()
	{
        if(true)
        return;



		if (photoList.size() > 0 && pidval.getText().length() > 0)
		{
			uploadButton.setVisibility(View.VISIBLE);

		}
		else
		{
			uploadButton.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)
	{

        super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_TAKE_PHOTO)
			// ������������յ�ͼƬ
			if (resultCode == Activity.RESULT_OK) // ��������

			{

				Log.d(TAG, photoFile.toString());
				File scaleFile = compressImageFile(photoFile);
				if (scaleFile != null) {
					photoFile = scaleFile;
				}


				photoList.add(photoFile.toString());


//                Log.d(TAG, "File:" + image.getAbsolutePath());
        RAUtil.updateGallery(photoFile.toString());
				StartCamera();
				// iPhotoCount++;
//				super.onActivityResult(requestCode, resultCode, data);

			}
			else
			{

				ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
				if (newVersion) {
					thumbsImageView = this.thumbsImageView;
				}
				if (photoList.size() > 0)
				{
					thumbBitmap =  BitmapFactory.decodeFile(photoList.get(photoList.size() - 1));
//
//
// ThumbnailUtils.extractThumbnail(BitmapFactory
//							.decodeFile(photoList.get(photoList.size() - 1)),
//							iwidth, iheight);
					if (thumbBitmap != null)
						thumbsImageView.setImageBitmap(thumbBitmap);
				}

				String photopath=photoFile.getAbsolutePath();
				photoFile.delete();
                RAUtil.updateGallery(photopath);
				TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
				if (newVersion) {
					countTextView = this.countTextView;
				}
				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_PREVIEW)
		{
			for (int i = 0; i < photoList.size(); i++)
			{
				File file = new File(photoList.get(i));
				if (!file.exists())
				{
					photoList.remove(i);
					i--;
				}
			}
			TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
			if (newVersion) {
				countTextView = this.countTextView;
			}
			countTextView.setText(photoList.size() + " Photos");
			if (photoList.size() == 0)
			{
				ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
				if (newVersion) {
					thumbsImageView = this.thumbsImageView;
				}
				thumbsImageView.setImageResource(R.drawable.no_pic);
				thumbBitmap = null;
			} else {
                thumbBitmap =  BitmapFactory.decodeFile(photoList.get(photoList.size() - 1));
//                        ThumbnailUtils.extractThumbnail(BitmapFactory
//								.decodeFile(photoList.get(photoList.size() - 1)),
//						iwidth, iheight);
				if (thumbBitmap != null)
					thumbsImageView.setImageBitmap(thumbBitmap);
			}
		}
		else if (requestCode == REQUEST_SCAN_BARCODE)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				Bundle bundle = data.getExtras();
				String pid = bundle.getString("pid");
				Log.d(TAG,
						"REQUEST_SCAN_BARCODE==========>pid="
								+ bundle.getString("pid"));
				if (newVersion) {

                    if (mode.equals("POP")||mode.equals("Returns"))
                    {
                        if(!RAUtil.isNumeric(pid))
                        {

                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("Warning")
                                    .setMessage(name+" must be a number")
                                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .show();
                            return;



//                            Toast toast = Toast.makeText(getApplicationContext(),
//                                    "Piid must be a number",
//                                    Toast.LENGTH_LONG);
//                            toast.setGravity(Gravity.CENTER, 0, 0);
//                            toast.show();
//                            return;
                        }

                    }
					pidval.setText(pid);
					updateUploadButton();

				} else  {
					TextView pidval = (TextView) findViewById(R.id.pidval);

					pidval.setText(pid);
					updateUploadButton();
				}
			}
		} else if (requestCode == REQUEST_MANUFACTURE) {
			if (resultCode == RESULT_OK) {
				String manufacture = data.getStringExtra("manufacture");
				setManufacture(manufacture);
			}
		}

	}

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

	// boolean confirm_upload()
	// {
	// boolean bret = false;
	// final Boolean b;
	//
	// return bret;
	// }
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (newVersion) {
			switch (item.getItemId()) {
				case R.id.upload_list_btn : {
					Intent intent = new Intent(this, TaskActivity.class);
					startActivity(intent);
				}
				break;
				case android.R.id.home: {
                    clear();
					finish();
				}
				break;
			}
			return super.onOptionsItemSelected(item);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
        Log.e(TAG, "onSaveInstanceState: photolist"+photoList.size());
		// 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.d(TAG, "save thumbpath==" + thumbpath);
		//outState.putInt("iPhotoCount", photoList.size());

		if (newVersion) {
			outState.putString("PIID", pidval.getText().toString());
			if (mode.equals("Model")) {
				outState.putString("Note",noteTextView.getText().toString());
				outState.putString("manufacture",manufacture);
			}
		} else  {
			TextView pidval = (TextView) findViewById(R.id.pidval);
			outState.putString("PIID", pidval.getText().toString());
		}
	}

	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);// ���ֽ��������λͼ
	}

    @Override
    public void onBackPressed() {
        clear();
        super.onBackPressed();
    }



    private void clear()
	{
        Log.e(TAG, "clear:" );
        for (int i = 0; i < photoList.size(); i++)
		{




            //应要求修改，退出上传界面后，不删除未传的图片

//            new File(photoList.get(i)).delete();
//            RAUtil.updateGallery(photoList.get(i));



		}
        photoList.clear();


	}

	private void clearfornew()
	{

        Log.e(TAG, "clearfornew: " );
        photoList.clear();
//		TextView pidval = (TextView) findViewById(R.id.pidval);
		pidval.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");

        manufacture_arr=null;
        setManufacture("");
		if(noteTextView!=null)
			noteTextView.setText("");

	}

	private final BroadcastReceiver	MainActivityReceiver	= new BroadcastReceiver()
															{

																public void onReceive(
																		Context context,
																		Intent intent)
																{
																	String action = intent
																			.getAction();
                                                                    if("REDANT.RAImage.UPLOAD_COMPLETE".equals(action))
                                                                    {

                                                                        String result = intent.getStringExtra("result");
                                                                        String message="";
                                                                        if(result.equals("finish"))
                                                                        {
                                                                            message="Upload complete.";
                                                                        }
                                                                        else
                                                                        {
                                                                            message="Upload complete with some warring.";
                                                                        }

//                                                                        Toast toast = Toast.makeText(getApplicationContext(),
//                                                                                message,
//                                                                                Toast.LENGTH_LONG);
//                                                                        toast.setGravity(Gravity.CENTER, 0, 0);
//                                                                        toast.show();


                                                                        new AlertDialog.Builder(MainActivity.this)
                                                                                .setTitle("Upload list")
                                                                                .setMessage(message)
                                                                                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                                                    @Override
                                                                                    public void onClick(DialogInterface dialog, int which) {

                                                                                    }
                                                                                })
                                                                                .show();
                                                                        Log.e("Finish_msg", "MainActivity onReceive: ");
                                                                    }
																}
															};

}
