package com.xuxin.mychat.activity;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.facedemo.FaceConversionUtil;
import com.example.facedemo.R;
import com.xuxin.mychat.mina.ChatClientHandler;
import com.xuxin.mychat.mina.ChatClientHandler.Callback;
import com.xuxin.mychat.mina.ChatClientSupport;

public class MainActivity extends Activity implements Callback {

	private EditText usernameET, connectET;

	private Button btn;

	private String userInfo, connectInfo;

	private List<String> list = new ArrayList<String>();

	private Spinner mySpinner;
	private ArrayAdapter<String> adapter;

	private static ProgressDialog dialog;

	private String httpUrl = "http://192.168.1.70:9080";

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

		// 读取头像信息
		new Thread(new Runnable() {
			@Override
			public void run() {
				FaceConversionUtil.getInstace().getFileText(getApplication());
			}
		}).start();

		list.add("内网");
		list.add("外网");

		dialog = new ProgressDialog(this);
		dialog.setTitle("正在登录.....");
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setCancelable(false);// 不可以用“返回键”取消

		usernameET = (EditText) findViewById(R.id.username);
		usernameET.append(getRndName());

		connectET = (EditText) findViewById(R.id.connectText);

		btn = (Button) findViewById(R.id.connectBtn);

		final ChatClientHandler handler = new ChatClientHandler(
				MainActivity.this);

		mySpinner = (Spinner) findViewById(R.id.Spinner_city);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mySpinner.setAdapter(adapter);
		mySpinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						String item = adapter.getItem(arg2);
						if (item.equals("内网")) {
							connectET.setText("192.168.1.70:12356");
							httpUrl = "http://192.168.1.70:9080";
						} else if (item.equals("外网")) {
							connectET.setText("118.26.40.118:12356");
							httpUrl = "http://118.26.40.118:9080";
						}

						arg0.setVisibility(View.VISIBLE);
					}

					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						// myTextView.setText("NONE");
						// arg0.setVisibility(View.VISIBLE);
					}
				});

		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				userInfo = usernameET.getText().toString();
				connectInfo = connectET.getText().toString();

				final ChatClientSupport client = new ChatClientSupport(
						userInfo, handler);
				final SocketAddress address = parseSocketAddress(connectInfo);

				new Thread() {
					@Override
					public void run() {
						try {
							if (!client.login(address)) {
								Log.i("xx", "login");
							}

						} catch (Exception e) {
							e.printStackTrace();
						} finally {
						}
					}
				}.start();

				dialog.show();
			}
		});

	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (1 == msg.what) {
				Toast.makeText(getApplicationContext(), msg.obj.toString(),
						Toast.LENGTH_LONG).show();
			}

		}

	};

	@Override
	public void messageReceived(String message) {//
		Log.i("client main <<< ", message);
		dialog.dismiss();
		String result = message.toString();
		if ("ok".equals(result)) {

			Intent intent = new Intent();
			intent.putExtra("userInfo", userInfo);
			intent.putExtra("connectInfo", connectInfo);
			intent.putExtra("httpUrl", httpUrl);

			intent.setClass(MainActivity.this,
					com.example.facedemo.ChatActivity.class);
			startActivity(intent);
		} else {
			Log.i("***", "toast");
			Message msg = new Message();
			msg.what = 1;
			msg.obj = result;
			mHandler.sendMessage(msg);
		}

	}

	private SocketAddress parseSocketAddress(String s) {
		s = s.trim();
		int colonIndex = s.indexOf(":");
		if (colonIndex > 0) {
			String host = s.substring(0, colonIndex);
			int port = parsePort(s.substring(colonIndex + 1));
			return new InetSocketAddress(host, port);
		} else {
			int port = parsePort(s.substring(colonIndex + 1));
			return new InetSocketAddress(port);
		}
	}

	private int parsePort(String s) {
		try {
			return Integer.parseInt(s);
		} catch (NumberFormatException nfe) {
			throw new IllegalArgumentException("Illegal port number: " + s);
		}
	}

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

	@Override
	public void connected(boolean flag) {
		// TODO Auto-generated method stub

	}

	@Override
	public void loggedIn() {

	}

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

	}

	@Override
	public void error(String message) {
		// TODO Auto-generated method stub

	}

	private String getRndName() {
		int x = (int) (Math.random() * 100);
		return "javaapk.com-" + x;
	}

}
