package com.qiyou.mb.android.ui.fragments;

import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.beans.basic.User_bean;
import com.qiyou.mb.android.utils.QiyouRestClient;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;

public class RegistFragment extends LoginFragment/*QiyouFragment*/ {

	@Override
	public void setFTag() {
		TAG = "com.qiyou.RegistFragment";
	}

	public static String getFTag() {
		return "com.qiyou.RegistFragment";
	}

	@Override
	public String getCurrentTag() {
		return "com.qiyou.RegistFragment";
	}

	public static RegistFragment newInstance() {
		RegistFragment f = new RegistFragment();
		return f;
	}

	 
	// Error Msg TextView Object
	TextView errorMsg;
	// Name Edit View Object
	EditText nameET;
	// Email Edit View Object
	EditText emailET;
	// Passwprd Edit View Object
	EditText pwdET;
	String password ;
	private Button btnRegister;
	private Button btnLinkToLoginScreen;
	Context context;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(!activity.is4Login)onBack();
		activity.updateActionBarTitle(R.string.frg_regist);
		context=activity.getApplicationContext();
		// activity=(MainActivity)getActivity();
		// activity.app.currentActiveFragment =TAG;
		vContainer = inflater.inflate(R.layout.register, container, false);
		initialView();
		return vContainer;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	void initialView() { 
 
		errorMsg = (TextView)vContainer.findViewById(R.id.register_error);
		// Find Name Edit View control by ID
		nameET = (EditText)vContainer.findViewById(R.id.registerName);
		// Find Email Edit View control by ID
		emailET = (EditText)vContainer.findViewById(R.id.registerEmail);
		// Find Password Edit View control by ID
		pwdET = (EditText)vContainer.findViewById(R.id.registerPassword);
		// Instantiate Progress Dialog object
		prgDialog = new ProgressDialog(activity);
		 
		btnRegister = (Button) vContainer.findViewById(R.id.btnRegister);
		btnRegister.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View view) {
	    	try {
	    		registNewUser();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	}
	    });
		btnLinkToLoginScreen = (Button) vContainer.findViewById(R.id.btnLinkToLoginScreen);
		btnLinkToLoginScreen.setOnClickListener(new OnClickListener() {
		    @Override
			public void onClick(View view) {
		    	 activity.showLogin();
		    	}
		    });
		
	 
	}

	/**
	 * Method gets triggered when Login button is clicked
	 * 
	 * @param view
	 * @throws JSONException 
	 * @throws UnsupportedEncodingException 
	 */
	public void registNewUser() throws JSONException, UnsupportedEncodingException {
		// Get Email Edit View Value
		// Get NAme ET control value
		String name = nameET.getText().toString();
		// Get Email ET control value
		String email = emailET.getText().toString();
		// Get Password ET control value
	    password = pwdET.getText().toString();
		// Instantiate Http Request Param Object
//		 name="guangyu3";
//		 email="1.qq@com";
//		 password="123456";
		 
		// When Email Edit View and Password Edit View have values other than
		// Null
		if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(name)) {
			
			if(TextUtils.indexOf(name, " ")>0){
				Toast.makeText(activity, "账户名不能有空格",
						Toast.LENGTH_LONG).show();
			}else
				if(name.length()<2){
					Toast.makeText(activity, "账户名太短了",
							Toast.LENGTH_LONG).show();
				}else
			
			// When Email entered is Valid
			if (QiYouConstant.DEVELOPER_MODE||Utils.validate(email)) {
				// Put Http parameter username with value of Email Edit View
				// control
				/*JSONObject json = new JSONObject();
				json.put("account", name);
				json.put("email", email);
	            json.put("passwd", Utils.getMD5Str(password));	            
	            postJsonWS(json.toString(),RestMethods.USER_P_SUBMIT"mb/user/");
	            QLog.getLogger().d(dTAG, "注册 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
	            QLog.getLogger().d(dTAG, json.toString());*/
//	            StringEntity entity = new StringEntity(json.toString());
//	           invokeWS(entity);
//	           postJsonWS(entity,"mb/user/login");
//	           params.put("json", strparams);
	           
//				params.put("username", email);
				// Put Http parameter password with value of Password Edit Value
				// control
//				params.put("password", password);
				// Invoke RESTful Web Service with Http parameters
//				invokeWS(params);
	            
	            User_bean u = new User_bean();
	            u.setPassword(Utils.getMD5Str(password));
	            u.setMail(email);
	            u.setAccount(name);		
	            u.setUserName(name);
			 	u.setLat(QiYouConstant.PV_LAST_LAT);
			 	u.setLon(QiYouConstant.PV_LAST_LON);
			 	u.setPhoneId(activity.app.getPhoneId());
	            QLog.getLogger().d(dTAG, Utils.getGsonString(u)); 
	            u.setLoginType(0);
			    postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_REGIST);
	        
	            
	            
			}
			// When Email is invalid
			else {
				Toast.makeText(activity, "请输入正确的邮箱",
						Toast.LENGTH_LONG).show();
			}
		}
		// When any of the Edit View control left blank
		else {
			Toast.makeText(activity,
					"请输入完整的注册信息",
					Toast.LENGTH_LONG).show();
		}

	}
 
	@Override
	void processJsonObject(String method,JSONObject response,String msg)throws JSONException{ 
		
		User_bean ub =(User_bean) Utils.getGsonObject(response.toString(), User_bean.class);
		QLog.getLogger().d(dTAG,"注册成功" );
		QLog.getLogger().d(dTAG,  response.toString() );
		Toast.makeText(activity, 
				"注册成功！",
				Toast.LENGTH_LONG).show();
		
		 activity.app.updateUserPref(ub);
		 activity.app.setAuth();
//		 getFragmentManager().popBackStack();
//		 onBack();
// 		 onBack();
		 updatePushAlias();
 		 activity.isTabHome();
//		 activity.app.updateUserPref(response.getInt("id"),
//				 response.getString("mail"),
//				 response.getString("account"),
//				 password  
//				 	);
	}
	
	
/*	void testCookies(){
//		  AsyncHttpClient client = new AsyncHttpClient(); 
			HttpContext httpContext = QiyouRestClient.getHttpContext();
			
			CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);//获取AsyncHttpClient中的CookieStore
			if(cookies!=null){
				for(Cookie c:cookies.getCookies()){
					QLog.getLogger().d(dTAG,"main before ~~"+c.getName()+","+c.getValue());
				}
			}else{
				QLog.getLogger().d(dTAG,"main  before~~,cookies is null");
			}
			
			//save cookie
			 PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
			 QiyouRestClient.setCookieStore(myCookieStore);
	        
			httpContext = QiyouRestClient.getHttpContext();
			cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
			if(cookies!=null){
				QLog.getLogger().d(dTAG, "main  after~~,cookies is not null");
				for(Cookie c:cookies.getCookies()){
					QLog.getLogger().d(dTAG,"main after ~~"+c.getName()+","+c.getValue());
				}
			}else{
				QLog.getLogger().d(dTAG, "main  after~~,cookies is null");
			}
			
	}*/
    
    @Override
	public boolean isShowBottomTabs() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void setTabOnFiling() {
		// TODO Auto-generated method stub

	}
	//http://blog.csdn.net/zhaoyazhi2129/article/details/26983145
	@Override
	public void showNotes(String notes,Boolean showToast){
		 if(TextUtils.isEmpty(notes))return; 
		 
		   Toast.makeText(activity,notes,Toast.LENGTH_SHORT ).show();
		  
	   }
}
