package com.lianxin.pubqq.main;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.lianxin.pubqq.R;
import com.lianxin.panqq.common.BaseActivity;
import com.lianxin.panqq.common.GloableParams;
import com.lianxin.panqq.common.NetUtil;
import com.lianxin.panqq.common.Utils;
import com.lianxin.panqq.client.callback.netCallBack;
import com.lianxin.panqq.client.logClient;
import com.lianxin.panqq.picker.ServipPickerDialog;
import com.lianxin.panqq.picker.UseridPickerDialog;
import com.lianxin.panqq.utils.CheckGetUtil;
import com.lianxin.panqq.utils.LoginUtil;
import com.lianxin.panqq.widget.CheckView;

//登陆模块
public class LoginActivity extends BaseActivity implements OnClickListener {
	public static String bakServerip = "";
	public static String bakUserid = "";		
	public static String bakPassword = "";
	public static String selServerip = "";	
	private String serverip;
	private String servername = "";	
	private String userId;		
	private String password;	
	private Button btn_login,btn_register;	
	private EditText txt_servip, txt_userid, txt_password;	
//	private ImageView img_servip,img_userid;
	private ImageButton img_servip,img_userid;
	private EditText txt_checkcode;	
    private CheckView mMyView = null;  
    private String[] checkNum = new String[4];  //获取每次更新的验证码，可用于判断用户输入是否正确 	
    private static String tmpServip = "";
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_login);
		super.onCreate(savedInstanceState);
		
		initControl();
		initView();
		initData();
		setListener();		
	}

//	@Override
	protected void initControl() {
		btn_login = (Button) findViewById(R.id.login_btn_login);		

		txt_servip = (EditText) findViewById(R.id.login_edit_severid);
		txt_userid = (EditText) findViewById(R.id.login_edit_account);
		txt_password = (EditText) findViewById(R.id.login_edit_pwd);
		img_servip = (ImageButton) findViewById(R.id.ImageButton01);
		img_servip.setVisibility(View.VISIBLE);
		img_userid = (ImageButton) findViewById(R.id.ImageButton02);
		img_userid.setVisibility(View.VISIBLE);	
		txt_checkcode = (EditText) findViewById(R.id.tv_user_checkcode);		
		mMyView = (CheckView) findViewById(R.id.checkView);
		// 初始化验证码
		checkNum = mMyView.getValidataAndSetImage();
		mMyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 重新初始化验证码
				checkNum = mMyView.getValidataAndSetImage();
			}
		});		
	}

	protected void initView() {

	}

	protected void initData() {
	    if(!TextUtils.isEmpty(bakServerip))
	    	txt_servip.setText(bakServerip);
	    if(!TextUtils.isEmpty(bakUserid))
	    	txt_userid.setText(bakUserid);
	    if(!TextUtils.isEmpty(bakPassword))
	    	txt_password.setText(bakPassword);
	    if(TextUtils.isEmpty(bakServerip))	    
	        LoadUser("");	    
	}

	protected void setListener() {
		btn_login.setOnClickListener(this);		
		img_servip.setOnClickListener(this);
		img_userid.setOnClickListener(this);
		txt_servip.addTextChangedListener(new IpTextChange());
		
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.img_back) {
			Utils.finish(LoginActivity.this);
		} else if (id == R.id.login_btn_login) {
			getLogin();
		} else if (id == R.id.ImageButton01) {
			new ServipPickerDialog(LoginActivity.this, ServipPickerDialog.THEME_HOLO_LIGHT, 0,
					new ServipPickerDialog.OnServSetListener() {
						@Override
						public void onSelect(String servip, String servname) {
							txt_servip.setText(servip);
							LoadUser(servip);
						}
					}).show();
		} else if (id == R.id.ImageButton02) {
			selServerip = txt_servip.getText().toString().trim();
			String ipaddress = txt_servip.getText().toString().trim();
			if (TextUtils.isEmpty(selServerip)) {
				Utils.showShortToast(LoginActivity.this, "请填写服务器ip地址！");
				txt_servip.requestFocus();
				return;
			}
			if (selServerip.length() < 7) {
				Utils.showShortToast(LoginActivity.this, "错误的服务器ip地址！");
				txt_servip.requestFocus();
				return;
			}
			new UseridPickerDialog(LoginActivity.this, UseridPickerDialog.THEME_HOLO_LIGHT, ipaddress,
					new UseridPickerDialog.OnUserSetListener() {
						@Override
						public void onSelect(String userid, String username) {
							txt_userid.setText(userid);
						}
					}).show();
		}
	}

	private void getLogin() {		
		serverip = txt_servip.getText().toString().trim();
		userId = txt_userid.getText().toString().trim();		
		password = txt_password.getText().toString().trim();
		if (TextUtils.isEmpty(serverip)){
			Utils.showShortToast(LoginActivity.this, "请填写服务器ip地址！");	
			txt_servip.requestFocus();			
            return;
	    }
		if (TextUtils.isEmpty(userId)){
			Utils.showShortToast(LoginActivity.this, "请填写用户账号！");
			txt_userid.requestFocus();			
            return;
	    }
		if (TextUtils.isEmpty(password)){
			Utils.showShortToast(LoginActivity.this, "请填写登录密码！");
			txt_password.requestFocus();			
            return;
	    }
		if (serverip.length() < 7){
			Utils.showShortToast(LoginActivity.this, "错误的服务器ip地址！");	
			txt_servip.requestFocus();			
            return;
	    }
		if (userId.length() < 3){
			Utils.showShortToast(LoginActivity.this, "错误的用户账号！");
			txt_userid.requestFocus();	
            return;
	    }
		if (password.length() < 5){
			Utils.showShortToast(LoginActivity.this, "错误的用户密码！");
			txt_password.requestFocus();			
            return;
	    }	
        String userInput = txt_checkcode.getText().toString();
        if(!CheckGetUtil.checkNum(userInput, checkNum)){
			Utils.showShortToast(LoginActivity.this, "验证码不对！");	
			txt_checkcode.requestFocus();			
            return;
	    }
		// 重新初始化验证码
		checkNum = mMyView.getValidataAndSetImage(); 
		if (!NetUtil.checkNetWork(context)) {
			Utils.showShortToast(LoginActivity.this, "网络不通！");			
			return;
		}		
		getLoadingDialog("正在登录...").show();
		
		getLogin(serverip,userId, password);
		//getLoadingDialog("正在登录...").setText("正在更新...");			
	}

	private void LoadUser(String servip) {

		if(servip=="")
		{
			String strip = LoginUtil.getLastLoginServIP();
			if(strip=="")
				return;
			serverip = strip;
			txt_servip.setText(serverip);			
		}
		//加载最近用户id、name
		serverip = txt_servip.getText().toString().trim();	
		String strid = LoginUtil.getLastLoginUserID( serverip );
		if(strid=="")
			return;
		userId = strid;
		txt_userid.setText(userId);		

	}

	private void SaveUser() {
  	 
		LoginUtil.saveLastLoginUser(serverip, userId);	

	}	

	private void getLogin(final String serverip,final String userId, final String password) {	
	
		logClient.logtoServer(serverip,userId, password, new netCallBack() {// 回调	

					@Override
					public void onError(int code, final String message) { 
						runOnUiThread(new Runnable() {
							public void run() {
								getLoadingDialog("正在登录...").dismiss();
								Utils.showLongToast(LoginActivity.this, message);
							}
						});	
						Utils.finish(LoginActivity.this);						
					}

					@Override				
					public void onSuccess(int code, String retMessage) {					
						runOnUiThread(new Runnable() {
							public void run() {
								getLoadingDialog("正在登录...").dismiss();	

								Utils.showLongToast(LoginActivity.this, "登陆成功！");	
								GloableParams.m_szServerIp = serverip;	
								//GloableParams.m_szUserId = userId;							
								//新用户初始化数据
								MyApp.getInstance().newUserLoginOk();								
						
								bakServerip = serverip;
								bakUserid = userId;		
								bakPassword = password;		

								//保存最近用户登录信息
								SaveUser();  
								MyApp.getInstance().initFilePath();									
						        //开始心跳线程
								MyApp.getInstance().startPingThread();	
								MyApp.getInstance().startUpdataThread();
						//		MyApp.getInstance().startHeartThread();								
							    Intent intent = new Intent(MyApp.getInstance().getNewUserLoginBroadcastAction()); 
							    intent.putExtra("mode", 1);							    
								MyApp.getInstance().sendBroadcast(intent); 								
							}
						});	
						//finish();
						Utils.finish(LoginActivity.this);						
					}
					/*@Override
					public void onSuccess(int code, Object contex) {					

						//finish();
						Utils.finish(LoginActivity.this);						
					}*/
					@Override
					public void onFailure(final int errorCode, final String message) {
		
						runOnUiThread(new Runnable() {
							public void run() {
								getLoadingDialog("正在登录...").dismiss();
								Utils.showLongToast(LoginActivity.this, message);								
							}
						});	
						//finish();	
						Utils.finish(LoginActivity.this);						
					}
				});
	}
	
	// EditText监听器
	class TextChange implements TextWatcher {

		@Override
		public void afterTextChanged(Editable arg0) {

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void onTextChanged(CharSequence cs, int start, int before,
				int count) {
	
		}
	}
	class IpTextChange implements TextWatcher {

		@Override
		public void afterTextChanged(Editable arg0) {
            String str = arg0.toString(); 
            if( str.length() == 0 || str.equals(tmpServip)) return; 
            tmpServip = checkIp(str); 
            txt_servip.setText(tmpServip); 
            txt_servip.setSelection(tmpServip.length()); 
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void onTextChanged(CharSequence cs, int start, int before,
				int count) {

		}
	}	
    private static String checkIp(String ip){ 
        String validStr = ".0123456789"; 
        StringBuffer sb = new StringBuffer(); 
        int i = 0; 
 
        for( i = 0; i < ip.length(); i++){ 
            if( validStr.indexOf(ip.charAt(i)) >= 0 ) sb.append(ip.charAt(i)); 
        } 
        if( sb.toString().length() == 0 ) return ""; 
 
        String newIP = ""; 
        String[] arrIp = sb.toString().split("\\."); 
        for( i = 0; i < arrIp.length && i < 4 ; i++){ 
            if( arrIp.equals("")) break;            
            if( i > 0 && i < 4 ) newIP += "."; 
            if( arrIp[i] == null ||arrIp[i].equals("") ){ 
            	//newIP += arrIp[i];
            }else if( Integer.parseInt(arrIp[i]) > 255 ){ 
                    newIP += String.format("%d", Integer.parseInt(arrIp[i])/10); 
            }else{             	
                newIP += arrIp[i]; 
            } 
      
        } 
        //if( i < 4 && sb.toString().endsWith("-")) newIP += "."; 
        if( i < 4 && sb.toString().endsWith(".")) newIP += ".";         
        return newIP; 

    } 
}
