package com.example.mountaintravel.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.smart.gtstrvl.ApplyActivity;
import com.smart.gtstrvl.EventInfoActivity;
import com.smart.gtstrvl.GameListActivity;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.R;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint({ "ValidFragment", "NewApi" })
public class CreateFrag extends Fragment {
	private Context context;
	Button createteam_button;
	EditText createteam_editText;
	TextView createteam_tverr;
	private SharedPreferences sp;

	public CreateFrag(Context context) {
		this.context = context;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return inflater
				.inflate(R.layout.activity_create_team, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		createteam_editText = (EditText) getView().findViewById(
				R.id.createteam_editText);
		createteam_tverr = (TextView) getView().findViewById(
				R.id.createteam_tverr);
		createteam_button = (Button) getView().findViewById(
				R.id.createteam_button);
		createteam_button.setOnClickListener(listener);
		super.onActivityCreated(savedInstanceState);
	}

	View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (TextUtils.isEmpty(createteam_editText.getText().toString()
					.trim())) {
				createteam_tverr.setVisibility(View.VISIBLE);
				createteam_tverr.setText("  名称不能为空");
				return;
			}
			if (createteam_editText.getText().toString().trim().length() > 5) {
				createteam_tverr.setVisibility(View.VISIBLE);
				createteam_tverr.setText("  名称不能超过五个字");
				return;
				// 有一个接口判断是否已注册过if
			}

			createteam_tverr.setVisibility(View.GONE);

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					loginByHttpClient();
				}

			}).start();
		}
	};
	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				ToastUtil.show(context, "创建成功");
				if (sp.getBoolean("apply", false)) {
					Intent intent = new Intent(context, GameListActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(context, EventInfoActivity.class);
					startActivity(intent);
				}
				break;
			case 2:
				ToastUtil.show(context, "该名称已被用");
				break;
			case 3:
				ToastUtil.show(context, "已经有了团队");
				break;

			case 4:
				ToastUtil.show(context, "创建失败");
				break;
			case 5:
				ToastUtil.show(context, "网络异常，请检查网络");
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void loginByHttpClient() {
		// TODO Auto-generated method stub
		String strURL = "http://" + Variable.address
				+ "/terminal/event/create_team";
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(strURL);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("eventId", ApplyActivity.eventId));
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("teamName",
					createteam_editText.getText().toString().trim()));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				// String result = StreamTools.streamToString(is);
				byte[] outMsgBytes = is.getBytes("UTF-8");
				String result = new String(outMsgBytes, "UTF-8");
				System.out.println(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (code.equals("000")) {
					Message message = new Message();
					message.what = 0;
					handler.sendMessage(message);

				} else if (code.equals("002")) {
					Message message = new Message();
					message.what = 2;
					handler.sendMessage(message);

				} else if (code.equals("003")) {
					Message message = new Message();
					message.what = 3;
					handler.sendMessage(message);

				} else {
					Message message = new Message();
					message.what = 4;
					handler.sendMessage(message);

				}
			} else {
				Message message = new Message();
				message.what = 5;
				handler.sendMessage(message);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}
}
