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

import java.io.UnsupportedEncodingException;

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

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

import com.loopj.android.http.RequestParams;
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.Utils;
import com.qiyou.mb.android.utils.log.QLog;
import com.qiyou.mb.android.utils.server.RestMethods;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

public class LoginFragment extends QiyouFragment {

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

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

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

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

	// Progress Dialog Object
//	ProgressDialog prgDialog;
	// Error Msg TextView Object
	TextView errorMsg;
	// account Edit View Object
	EditText accountET;
	// Passwprd Edit View Object
	EditText pwdET;
	private Button btnLogin,btnLogout;
	private Button btnLinkToRegisterScreen;
	private Button btnQQLogin;
	Context context;
//	String account  ;
	String mail;
	// Get Password Edit View Value
	String password  ;
	// Instantiate Http Request Param Object
	ScrollView	textContainer;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

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

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		 textContainer =(android.widget.ScrollView)vContainer.findViewById(R.id.td_scrollView); 		  
		  if(textContainer!=null)
		     textContainer.setOnTouchListener(new OnTouchListener() {
			    @Override
			    public boolean onTouch(View v, MotionEvent event) {
	 		        Utils.hideSoftKeyboard(activity);
			        return false;
			    }
			});
		 
	}

	void initialView() {

//		errorMsg = (TextView) vContainer.findViewById(R.id.login_error);
		// Find account Edit View control by ID
		accountET = (EditText) vContainer.findViewById(R.id.loginAccount);
		// Find Password Edit View control by ID
		pwdET = (EditText) vContainer.findViewById(R.id.loginPassword);
		// Instantiate Progress Dialog object
//		if(activity.app.user.getUserbean()!=null){
//			accountET.setText(activity.app.user.getUserbean().getAccount());
//		}
	
		if(activity.app.user.getUserbean()!=null 
				&&activity.app.user.getUserbean().getLoginType()==0){
 			accountET.setText(activity.app.user.getUserbean().getMail());
 		}
			
		btnQQLogin= (Button) vContainer.findViewById(R.id.btnQQLogin);
		btnQQLogin.setOnClickListener(new OnClickListener() {
		    @Override
			public void onClick(View view) { 
		    	 doQQLogin();
		    	}
		    });
		btnLinkToRegisterScreen = (Button) vContainer.findViewById(R.id.btnLinkToRegisterScreen);
		btnLinkToRegisterScreen.setOnClickListener(new OnClickListener() {
		    @Override
			public void onClick(View view) {
		    	activity.is4Login=true;
		    	 activity.showRegist();
		    	}
		    });
		btnLogin =(Button) vContainer.findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {
	    @Override
		public void onClick(View view) {
	    	try {
	    		 Utils.hideSoftKeyboard(activity);
	    		activity.is4Login=false;
				loginUser();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	}
	    });
		
		
		btnLogout = (Button) vContainer.findViewById(R.id.btnLogout);
		btnLogout.setOnClickListener(new OnClickListener() {
		    @Override
			public void onClick(View view) {
		    	logout();
//			    	activity.app.logout();
//			    	Toast.makeText(activity, "您已登出",Toast.LENGTH_SHORT).show();
//			    	activity.isTabHome(); 
		    	
		    	}
		    });
		btnLogout.setVisibility(activity.app.user.getUserbean().getId() > 0 ? View.VISIBLE:View.GONE);
		btnLogout.setVisibility(View.GONE);
		
		initalCurrentLoginUserVuew();
	}

	void initalCurrentLoginUserVuew(){
		TextView tv =(TextView)vContainer.findViewById(R.id.current_loginAccount); 
		
		 if(activity.app.user.getUserbean().getId()<=0 
//				 || this.getUser().getLoginType()==0 && activity.app.user.getUserbean().getExprires()==0
				 ){
			 tv.setVisibility(View.GONE);
			 return;
		 }
		 tv.setVisibility(View.VISIBLE);
		 
		 
	    String loginTitle  = activity.app.user.getUserbean().getId()<=0?"": 
	    					  activity.app.user.getUserbean().getUserName()/*.getAccount()*/ ;

	    int loginType =activity.app.user.getUserbean().getLoginType();
	    tv.setText("登录状态");
	     tv.setText(String.format("当前已登录%s：%s",loginType==1?"(QQ认证用户)":"用户", loginTitle )) ;
	    
	    
	    
	    
	    
	}
	
	
	/**
	 * Method gets triggered when Login button is clicked
	 * 
	 * @param view
	 * @throws JSONException 
	 * @throws UnsupportedEncodingException 
	 */
	public void loginUser() throws JSONException, UnsupportedEncodingException {
		// Get account Edit View Value
		 /* account*/mail = accountET.getText().toString();
		// Get Password Edit View Value
		  password = pwdET.getText().toString();
		  password= Utils.getMD5Str(password);
		// Instantiate Http Request Param Object
//		  RequestParams params = new RequestParams();
		// When account Edit View and Password Edit View have values other than
		// Null
		  
		  if( !Utils.validate(mail)) {
				Toast.makeText(activity, "请输入您注册用的邮箱",
						Toast.LENGTH_LONG).show();
				return;
			}
		  
		if (!TextUtils.isEmpty(mail) && !TextUtils.isEmpty(password)  ) {
			// When account entered is Valid
//			if (QiYouConstant.DEVELOPER_MODE||Utils.validate(account)) {
				// Put Http parameter username with value of account Edit View
				// control
		/*		JSONObject json = new JSONObject();
	            json.put("mail", mail);
	            json.put("passwd", Utils.getMD5Str(password));
	            json.put("phoneid", activity.app.getPhoneId());*/
	            User_bean u =new User_bean();
	            u.setMail(mail);
	            u.setPassword(password);
	            u.setPhoneId(activity.app.getPhoneId());
		 	 
//	            setCookie();
	            postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_USER_LOGIN/*"mb/user/login"*/);
	            QLog.getLogger().d(dTAG, "登陆。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
	            QLog.getLogger().d(dTAG, Utils.getGsonString(u));
//	           StringEntity entity = new StringEntity(json.toString()); 
//	           invokeWS(entity);
//	           postJsonWS(entity,"mb/user/login");
	           
//	           params.put("json", strparams);
	           
//				params.put("username", account);
				// Put Http parameter password with value of Password Edit Value
				// control
//				params.put("password", password);
				// Invoke RESTful Web Service with Http parameters
////				invokeWS(params);
//			}
//			// When account is invalid
//			else {
//				Toast.makeText(activity, "账号输入错误",
//						Toast.LENGTH_LONG).show();
//			}
		}
		// When any of the Edit View control left blank
		else {
			this.showNotes("登录邮箱和密码不能为空", true);
		}

	}
 
	
	
	@Override
	void processJsonObject(String method,JSONObject response,String msg) throws JSONException{
		activity.app.setLastStatSyncTime(0);
		 User_bean ub =(User_bean) Utils.getGsonObject(response.toString(), User_bean.class);
		 if(TextUtils.isEmpty(ub.getUserName()) 
				 && !TextUtils.isEmpty(ub.getAccount())){
			 ub.setUserName(ub.getAccount());
		 }
		 activity.app.user.setUserbean(ub);
		 activity.app.updateUserPref(ub);
		 activity.app.setAuth();
		 updatePushAlias();
//		 initPrgDialog();
//		 activity.app.mStatistics=null;//new Statistics();
		 activity.app.isNewLogin=true;
		 activity.app.syncStatistics();



		 QLog.getLogger().d(dTAG, TAG+" response user:" +response.toString());
		/* activity.app.updateUserPref(response.getInt("id"),
				 response.getString("mail"),
				 response.getString("account"),
				 password ,
				 response.getString("title"),
				 response.getInt("score"),
				 response.getInt("paiming")
				 	);*/ 
//		 setCookie();
		 
		 onBack();//返回 
		
//		 new Thread(){
//			   public void run() {
//			    try{
//			     Instrumentation inst = new Instrumentation();
//			     inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
//			    }
//			    catch (Exception e) {
//			                 Log.e("Exception when onBack", e.toString());
//			             }
//			   }
//			  }.start();

			  
	}

	protected void updatePushAlias(){
		if ( activity.app.user.getUserbean().getId() > 0) {
			PushAgent mPushAgent = PushAgent.getInstance(activity);
			String id = activity.app.user.getUserbean().getId()+"";
//			id = 951+"";
			mPushAgent.addAlias(id ,"i7lvid", new UTrack.ICallBack() {
				@Override
				public void onMessage(boolean isSuccess, String message) {
					QLog.getLogger().d(dTAG, "   alia is success ?" + isSuccess +"," + message);
				}
			});
		}

	}


	String SCOPE = "get_simple_userinfo,add_topic";//所有权限用“all”
	public void doQQLogin() {
		IUiListener listener = new BaseUiListener() {
			@Override
			protected void doComplete(/*JSONObject*/Object values) {
				onAuth20LoginComplete(values);
			}
		};
		activity.mTencent.login(this, SCOPE, listener);
		QLog.getLogger().d(dTAG, " QQ Login begin......");
	}

	private void onAuth20LoginComplete(Object values){
		
		try {
			JSONObject json =(JSONObject)values;
			QLog.getLogger().d(dTAG, json.toString());
			QiYouConstant.PV_OPEN_ID =json.getString("openid");
			QiYouConstant.PV_ACCESS_TOKEN =json.getString("access_token");
			QiYouConstant.PV_EXPIRES_IN =System.currentTimeMillis()+Long.parseLong(json.getString("expires_in"))*1000;
		    activity.app.saveAuth20Token();
		    
//		    activity.mTencent.request(SocialConstants. arg1, arg2)
		    String url="https://graph.qq.com/user/get_user_info" ;//?access_token=YOUR_ACCESS_TOKEN&oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID
		    
		    RequestParams params = new RequestParams();
		    params.put("access_token", QiYouConstant.PV_ACCESS_TOKEN);
		    params.put("oauth_consumer_key", QiYouConstant.TENCENT_APP_ID);
		    params.put("openid", QiYouConstant.PV_OPEN_ID);
		     
		    get3dJsonWs(params,url,false);
		 
		    
		   
		    
		    
		    
		    
			 
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		QLog.getLogger().d(dTAG, " QQ Login get response and begin to request user info from qq...");
	}
	
	
	@Override
	void process3dpartJson(JSONObject response) throws JSONException{
		QLog.getLogger().d(dTAG, "  user info from qq success...");
		
		 if(response==null)return;
		 
//		 figureurl
		 
		 User_bean u = new User_bean();
		 	u.setQqOpenId(QiYouConstant.PV_OPEN_ID);
		 	u.setQqExprires(QiYouConstant.PV_EXPIRES_IN);
 		 	u.setQqToken(QiYouConstant.PV_ACCESS_TOKEN ); 
		 	u.setQqAbulmUrl(response.getString("figureurl_qq_1"));
		 	u.setQqName(response.getString("nickname")); 
		 	u.setUserName(response.getString("nickname"));
		 	u.setAccount(QiYouConstant.PV_OPEN_ID);
		 	u.setLat(QiYouConstant.PV_LAST_LAT);
		 	u.setLon(QiYouConstant.PV_LAST_LON);
		 	u.setLoginType(1);
		 	u.setPhoneId(activity.app.getPhoneId());
         postJsonWS(Utils.getGsonString(u),RestMethods.USER_P_USER_LOGIN/*"mb/user/login"*/);
 		QLog.getLogger().d(dTAG, " QQ Login get response and syncing with i7lv...");
	 }
	
	
	 @Override
	public void showNotes(String notes,Boolean showToast){
		 if(TextUtils.isEmpty(notes))return; 
		 
		 if(vContainer==null)return;
		   TextView txtNote=(TextView)vContainer.findViewById(R.id.txtNotice);
		   if(txtNote!=null){				   
			   txtNote.setText(notes);
			   txtNote.setVisibility(View.VISIBLE);
		   }
		  
	   } 
	
    
    @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
	private class BaseUiListener implements IUiListener {
		@Override
		public void onComplete(Object response) {
		     //V2.0版本，参数类型由JSONObject 改成了Object,具体类型参考api文档
//		mBaseMessageText.setText("onComplete:");
			QLog.getLogger().d(dTAG, "Tencent Auth2.0 on Complete.");
		doComplete(response);
		}
		protected void doComplete(/*JSONObject*/Object values) {

		}
		@Override
		public void onError(UiError e) {
			QLog.getLogger().e("onError:", "code:" + e.errorCode + ", msg:"
		+ e.errorMessage + ", detail:" + e.errorDetail);
		}
		@Override
		public void onCancel() {
//		showResult("onCancel", "");
		}
		 
		}
	@Override
	void asynClientOnFailure(int statusCode,String msg, org.apache.http.Header[] headers){
		 super.asynClientOnFailure(statusCode, msg, headers);
     if (statusCode == 417) {
		 
			showNotes("出错了，错误信息："+msg,true);
		}
		// When Http response code other than 404, 500
	 
	}
}
