package com.example.client;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends Activity implements OnClickListener{
	EditText userName01,password01,password02;
	Button back,register01;
	
	EditText mRealnameEditText;
	EditText mAgeEditText;
	private Spinner mSexSpinner; 
	
	private String mSexString;
	
	SqlHelper db;
	SQLiteDatabase sDatabase = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.register);
        
        userName01 = (EditText)findViewById(R.id.login_user_edit);
        password01 = (EditText)findViewById(R.id.login_passwd_edit);
        password02 = (EditText)findViewById(R.id.login_repasswd_edit);
        
        mRealnameEditText = (EditText)findViewById(R.id.login_name_edit);
        mAgeEditText = (EditText)findViewById(R.id.login_age_edit);
        
        back = (Button)findViewById(R.id.register_reback_btn);
        register01 = (Button)findViewById(R.id.register_btn);
        
        back.setOnClickListener(this);
        register01.setOnClickListener(this);
        
        // 下拉选择框设置
        mSexSpinner = (Spinner)findViewById(R.id.spinnerSex);
        String[] items = {"男", "女"};
        ArrayAdapter<String> _Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        mSexSpinner.setAdapter(_Adapter);
        mSexSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = parent.getItemAtPosition(position).toString();
                
                mSexString = str;
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });

		db = new SqlHelper(getApplicationContext(), "store.db", null, 1);
		sDatabase = db.getWritableDatabase();        
        
    }
    
    @Override
    protected void onDestroy() {
        finish();
        super.onDestroy();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		
		 if(id == R.id.register_reback_btn){ 
			 Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);			 
			 startActivity(intent);
		 }
		 
		 if(id == R.id.register_btn){
		        int ageValue = 0;
		        if (!mAgeEditText.getText().toString().equals("")
		        		&& this.isNumeric(mAgeEditText.getText().toString()) )
		        {
		            ageValue = Integer.valueOf(mAgeEditText.getText().toString());
		        }
		     
				if (userName01.getText().toString().equals("")
						|| password01.getText().toString().equals("")
						|| password02.getText().toString().equals("")
						|| mRealnameEditText.getText().toString().equals("")
						|| mAgeEditText.getText().toString().equals("")) {

					Toast.makeText(this, "请填写完整信息！", Toast.LENGTH_SHORT).show();
				} else if (!password01.getText().toString().equals(password02.getText().toString())) {
					Toast.makeText(this, "两次密码输入不一致！", Toast.LENGTH_SHORT).show();
				} else if (ageValue <= 0 || ageValue > 100 
						|| !this.isNumeric(mAgeEditText.getText().toString())) {
					Toast.makeText(this, "请输入合法的年龄！", Toast.LENGTH_SHORT).show();
				} else if (mRealnameEditText.getText().toString().length() < 2 
						|| mRealnameEditText.getText().toString().length() > 4) {
					Toast.makeText(this, "请输入合法的中文姓名(2到4个汉字)！", Toast.LENGTH_SHORT).show();
				} else if ( !isChinese(mRealnameEditText.getText().toString()) ) {
					Toast.makeText(this, "请输入真实的中文姓名！", Toast.LENGTH_SHORT).show();
                }else {
					this.register();
				}	
		 }
			
	}	
	
	
	private void register() {
	    String ename = userName01.getText().toString();
        String epass = password01.getText().toString();
        
        String realname = mRealnameEditText.getText().toString();
        String age = mAgeEditText.getText().toString();
        
        // 查询语句
        String selectStr = "select username from user_info";
        Cursor select_cursor = sDatabase.rawQuery(selectStr, null);                 
        select_cursor.moveToFirst();
        String string = null;
        do {
            try {
                string = select_cursor.getString(0);
            } catch (Exception e) {
                // TODO: handle exception
                string = "";
            }
            if (string.equals(ename)) {
            	Toast.makeText(this, "用户名已存在，请另设用户名！", Toast.LENGTH_SHORT).show();
                select_cursor.close();
                break;

            }
        }while (select_cursor.moveToNext());
        
        // 没有重名注册开始
        if (!string.equals(ename)) {
            // 定义ID
            int id1 = 0;
            String select = "select max(_id) from user_info";
            Cursor seCursor = sDatabase.rawQuery(select, null);
            try {
                seCursor.moveToFirst();
                id1 = Integer.parseInt(seCursor.getString(0));
                id1 += 1;
            } catch (Exception e) {
                // TODO: handle exception
                id1 = 0;
            }
            sDatabase.execSQL("insert into user_info values('" + id1 + "','"
                    + ename + "','" + epass + "','" + realname + "','" + age + "','" + mSexString + "')" 
                    );
            
            Toast.makeText(RegisterActivity.this, "注册成功!", 2000).show();
            Intent intent = new Intent(this, LoginActivity.class);
            this.startActivity(intent);  
            
            seCursor.close();
        }
	}
	
	
	public boolean isNumeric(String str){ 
	    Pattern pattern = Pattern.compile("[0-9]*"); 
	    return pattern.matcher(str).matches();    
	} 
	
	// 判断是否为中文字符串
	private boolean isChinese(String str)
	{
	    boolean isCn = true;
	    
	    Pattern p;
	    Matcher m;

	    p = Pattern.compile("[\\u4e00-\\u9fa5]");
	    
	    for(int i = 0 ;i < str.length(); i++)
	    {
	        m = p.matcher( str.substring(i, i + 1) );
	        if ( !m.find() ) {
	            isCn = false;
	        }
	    }

	    return isCn;
	}
}

