package com.usai.redant.raimage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class ServerSettingActivity extends Activity
{
	static final int	REQUEST_SCAN_BARCODE	= 2;

//	public boolean checkCameraPermission() {
//		int permission = ContextCompat.checkSelfPermission(ServerSettingActivity.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;
//	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_service_setting);

		SharedPreferences pref = RedAntApplication.getInstance()
				.getSharedPreferences("RA Image", 0);

//		String ia = pref.getString("ia", null);
//		String ea = pref.getString("ea", null);
		String aa = pref.getString("aa", null);
		String station_name = pref.getString("station name", null);
//		RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);

//		if (!TextUtils.isEmpty(aa) && aa.equals(ia))
//			rg.check(R.id.radio0);

//		if (!TextUtils.isEmpty(aa) && aa.equals(ea))
//			rg.check(R.id.radio1);

		EditText et_ia = (EditText) findViewById(R.id.et_ia);
//		EditText et_ea = (EditText) findViewById(R.id.et_ea);
		EditText et_name = (EditText) findViewById(R.id.et_name);
//		et_ea.setText(ea);
		et_ia.setText(aa);
		et_name.setText(station_name);

		ImageButton ibtn = (ImageButton) findViewById(R.id.ibtn_scan);
		ibtn.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
			//	Log.d(TAG, "==============>Click Scan button");
//				if (!RAUtil.checkPermission(ServerSettingActivity.this,"android.permission.CAMERA")) {
//
//					return;
//				}

				Intent intent = new Intent();

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

			}
		});
	}

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

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{

		if (requestCode == REQUEST_SCAN_BARCODE)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				Bundle bundle = data.getExtras();
				String jstr = bundle.getString("pid");
				
				if (jstr == null || jstr.length() <= 0)
				{
					//Log.d(TAG, "json is wrong");
					toast();
					return ;//Network.RESULT_NET_ERROR;
				}	
				String address[]=jstr.split(";");
				EditText et_ia = (EditText) findViewById(R.id.et_ia);
//				EditText et_ea = (EditText) findViewById(R.id.et_ea);
				EditText et_name = (EditText) findViewById(R.id.et_name);
				if (address.length==3)
				{
					et_ia.setText(address[2].trim());
					et_name.setText(address[0].trim());
				}
				else if(address.length==2)
				{
					et_ia.setText(address[1].trim());
					et_name.setText(address[0].trim());
				}
				else
				{
					toast();
					return;
				}

//				et_ea.setText(address[2].trim());

//				JSONObject jsobj;
//				try
//				{
//					jsobj = new JSONObject(jstr);
//					if (jsobj.length() > 0)
//					{
//						String name = jsobj.getString("name");
//						String ia = jsobj.getString("ia");
//						String ea = jsobj.getString("ea");
//						EditText et_ia = (EditText) findViewById(R.id.et_ia);
//						EditText et_ea = (EditText) findViewById(R.id.et_ea);
//						et_ea.setText(ea);
//						et_ia.setText(ia);
////						int iresult = jsobj.getInt("result");
////						if (iresult == Network.AP_USER_AUTH)
////						{
////							return ;//RESULT_TRUE;
////						}
////
////						else
////						{
////
////							return ;//RESULT_FALSE;
////						}
//					}
//					return ;
//				}
//				catch (JSONException e)
//				{
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					return ;
//				}
				//Log.d(TAG,
//						"REQUEST_SCAN_BARCODE==========>pid="
//								+ bundle.getString("pid"));
//				TextView pidval = (TextView) findViewById(R.id.pidval);
//				pidval.setText(pid);
//				updateUploadButton();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@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_save)
		{
			EditText et_ia = (EditText) findViewById(R.id.et_ia);
//			EditText et_ea = (EditText) findViewById(R.id.et_ea);
			EditText et_name = (EditText) findViewById(R.id.et_name);
			String ia = et_ia.getText().toString();
//			String ea = et_ea.getText().toString();
			String name = et_name.getText().toString();
			if (TextUtils.isEmpty(ia) )
			{
				showdialog("Server address can not be empty!");
				return true;
			}

			SharedPreferences pref = RedAntApplication.getInstance()
					.getSharedPreferences("RA Image", 0);
			SharedPreferences.Editor editor = pref.edit();




			if (TextUtils.isEmpty(name))
			{
				showdialog("Station name can not be empty!");
				return true;
			}
			else {
				
				editor.putString("station name", name);
			}
			if (!TextUtils.isEmpty(ia))
			{

				if (!ia.substring(ia.length() - 1).equals("/"))
					ia = ia + "/";
				editor.putString("aa", ia);
				RedAntApplication.active_address = ia;

			}
//			if (!TextUtils.isEmpty(ea))
//			{
//				if (!ea.substring(ea.length() - 1).equals("/"))
//					ea = ea + "/";
//				editor.putString("ea", ea);
//			}
//			RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
//			if (rg.getCheckedRadioButtonId() == R.id.radio0)
//			{
//				if (!TextUtils.isEmpty(ia))
//				{
//					editor.putString("aa", ia);
//					RedAntApplication.active_address = ia;
//				}
//				else
//				{
//					showdialog("Active server address can not be empty!");
//					return true;
//				}
//			}
//			else
//			{
//				if (!TextUtils.isEmpty(ea))
//				{
//					editor.putString("aa", ea);
//					RedAntApplication.active_address = ea;
//				}
//				else
//				{
//					showdialog("Active server address can not be empty!");
//					return true;
//				}
//			}

			RedAntApplication.station_name = name;

			editor.remove("Lat");
			editor.remove("Lon");
			editor.commit();
			//sendBroadcast(new Intent("REDANT.POP.RESET_LOCATION"));


			String result = pref.getString("aa","");
			Intent intent = new Intent();
			intent.putExtra("server", result);
                /*
                 * 调用setResult方法表示我将Intent对象返回给之前的那个Activity，这样就可以在onActivityResult方法中得到Intent对象，
                 */
			setResult(1001, intent);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void toast()
	{
		Toast toast = Toast.makeText(this,"Wrong server setting format",
				Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	private void showdialog(String msg)
	{
		new AlertDialog.Builder(ServerSettingActivity.this)
				.setIcon(android.R.drawable.ic_dialog_info).setTitle("Error!")
				.setMessage(msg)
				.setPositiveButton("OK", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int whichButton)
					{

						// finish();
						/* User clicked OK so do some stuff */
					}
				}).show();
	}
}
