package app.hima.activity.fragment;

import java.util.concurrent.ExecutionException;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import app.hima.R;
import app.hima.net.SendMessage;
import app.hima.tool.MessageAdapter;

public class WallFragment extends Fragment {
	private EditText messageEdit;
	private Button sendButton;
	private ListView listView;
	private MessageAdapter adapter;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_mur,	container, false);
			this.messageEdit = (EditText) rootView.findViewById(R.id.wallTextEdit);
			this.sendButton = (Button) rootView.findViewById(R.id.wallSendButton);
			this.listView = (ListView) rootView.findViewById(R.id.messageList);
			
			this.adapter = new MessageAdapter(getActivity());
			
			Button reload = new Button(getActivity());
			reload.setText("更新");
			reload.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					adapter.reload();
				}
			});
			
			this.listView.addHeaderView(reload);
			this.listView.setAdapter(this.adapter);
			
			final EditText editText = this.messageEdit;
			
			this.sendButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String message = editText.getText().toString();
					if(message == null || message.length() < 2)
						return;
					try {
						new SendMessage().execute(message).get();
						editText.setText("");
						reloadList();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
				}
			});
			
			this.adapter.reload();
			
			return rootView;
		}
		
		private void reloadList() {
			this.adapter.reload();
		}
		
		@Override
		public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			inflater.inflate(R.menu.wall, menu);
			super.onCreateOptionsMenu(menu, inflater);
		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case R.id.refresh:
				reloadList();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
}
