package cn.ccy.test_weather;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
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.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.ccy.test_weather.adapter.ListAdapter;
import cn.ccy.test_weather.location.AutoLocation;
import cn.ccy.test_weather.utils.GetProvinceOrCity;
import cn.ccy.test_weather.utils.ParseDetail;
import cn.ccy.test_weather.utils.SaveProvinceOrCityMsg;
import cn.ccy.test_weather_model.WeatherDetail;
import cn.ccy.text_weather.services.GetWeatherService;

public class MainActivity extends Activity {

	public static TextView ShowWeatherCurrent;
	public static TextView ShowWeatherToday;
	public static TextView ShowupdateTime;
	private Spinner ProcinceSpinner;
	private Spinner CitySpinner;
	private Button manual;
	private Button location;
	private static String city;
	private static List<String> provinces = null;
	private ListAdapter CityAdapter;
	private ListAdapter ProvinceAdapter;
	public static Handler handler;
	public static Runnable runnable;
	public static Runnable runnable2;
	public static Runnable runnable3;
	public static SoapObject detail;
	private Intent i;
	private Intent intent;
	private static ProgressDialog progressBar;
	static AlertDialog.Builder builder;
	public static LinearLayout SelectView;
	static WeatherDetail detailContent;
	static ParseDetail pd;
	private boolean flag = true;
	private FileInputStream fis;
	private long lastClickTime = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		System.out.println("--- onCreate---");

		// save = (Button) findViewById(R.id.save);
		manual = (Button) findViewById(R.id.Manual);
		location = (Button) findViewById(R.id.location);
		manual.setOnClickListener(new ManualClickListerner());

		location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				progressBar = new ProgressDialog(MainActivity.this);
				handler.post(runnable3);
				FutureTask<SoapObject> task = new FutureTask<SoapObject>(
						new Callable<SoapObject>() {
							@Override
							public SoapObject call() throws Exception {
								intent = new Intent();
								intent.setClass(MainActivity.this,
										AutoLocation.class);
								startService(intent);

								return null;
							}
						});
				new Thread(task).start();

			}
		});

		runnable = new Runnable() {
			@Override
			public void run() {
				progressBar.setCancelable(false);
				progressBar.setMessage("正在加载省份和城市...");
				progressBar.setIndeterminate(false);
				progressBar.setCanceledOnTouchOutside(false);
				progressBar.show();
			}
		};
		runnable2 = new Runnable() {
			@Override
			public void run() {
				progressBar.setCancelable(false);
				progressBar.setMessage("更新天气中...");
				progressBar.setIndeterminate(false);
				progressBar.setCanceledOnTouchOutside(false);
				progressBar.show();
			}
		};
		runnable3 = new Runnable() {
			@Override
			public void run() {
				progressBar.setCancelable(false);
				progressBar.setMessage("定位中...");
				progressBar.setIndeterminate(false);
				progressBar.setCanceledOnTouchOutside(false);
				progressBar.show();
			}
		};

		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 0x1233) {
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							progressBar.dismiss();
							finish();
							if (intent != null)
								stopService(intent);
						}
					}, 700);

					i = new Intent(MainActivity.this, ShowWeatherView.class);
					// i.setFlags(BIND_AUTO_CREATE);
					startActivity(i);
				}
				if (msg.what == 0x1234) {
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							progressBar.dismiss();
						}
					}, 700);

					try {
						provinces = GetProvinceOrCity
								.getProvinceMsg(MainActivity.this);
					} catch (IOException e) {
						Log.v("Exception", "GetProvinceMsg返回失败");
						e.printStackTrace();
					}
					ProvinceAdapter = new ListAdapter(MainActivity.this,
							provinces);
					ProcinceSpinner.setAdapter(ProvinceAdapter);

					ProcinceSpinner
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {
									List<String> cities = null;
									try {
										cities = GetProvinceOrCity
												.getCityMsg(ProcinceSpinner
														.getSelectedItem()
														.toString());
									} catch (IOException e) {
										Log.v("Exception", "GetCityMsg返回失败");
										e.printStackTrace();
									}
									// 显示城市列表
									CityAdapter = new ListAdapter(
											MainActivity.this, cities);
									CitySpinner.setAdapter(CityAdapter);
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
								}

							});

					// 显示天气实况
					CitySpinner
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {
									city = CitySpinner.getSelectedItem()
											.toString();

								}

								public void onNothingSelected(
										AdapterView<?> arg0) {
								}
							});

					builder = new AlertDialog.Builder(MainActivity.this)
					// 设置对话框标题
							.setTitle("您所在的地理位置：")
							// 设置图标
							.setIcon(R.drawable.ic_launcher)
							// 设置简单的列表项内容
							.setView(SelectView);
					// 为AlertDialog.Builder添加【确定】按钮
					setPositiveButton(builder, MainActivity.this);
					// 为AlertDialog.Builder添加【取消】按钮
					setNegativeButton(builder, MainActivity.this).create()
							.show();

				}
			};
		};
	}

	class ManualClickListerner implements View.OnClickListener {

		@Override
		public void onClick(View v) {

			SelectView = (LinearLayout) getLayoutInflater().inflate(
					R.layout.select_spinner_view, null);
			ProcinceSpinner = (Spinner) SelectView
					.findViewById(R.id.ProvinceSpinner);
			CitySpinner = (Spinner) SelectView.findViewById(R.id.CitySpinner);

			progressBar = new ProgressDialog(MainActivity.this);

			try {
				fis = openFileInput("ProvinceOrCityMsg");

			} catch (FileNotFoundException e) {
				flag = false;
				
				e.printStackTrace();
			}

			if (!flag) {
				System.out.println("第一次手动定位！");
				handler.post(runnable);

				Toast.makeText(MainActivity.this, "第一次加载可能比较慢，请耐心等待！",
						Toast.LENGTH_LONG).show();

				FutureTask<Properties> task = new FutureTask<Properties>(
						new Callable<Properties>() {
							public Properties call() throws Exception {
								return SaveProvinceOrCityMsg
										.saveProAndCityMsg(MainActivity.this);
							}
						});
				new Thread(task).start();

			} else
				handler.sendEmptyMessage(0x1234);
		}

	}

	public static AlertDialog.Builder setPositiveButton(
			AlertDialog.Builder builder, final Context context) {
		// 调用setPositiveButton方法添加确定按钮
		return builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						progressBar = new ProgressDialog(context);
						handler.post(runnable2);
						FutureTask<SoapObject> task = new FutureTask<SoapObject>(
								new Callable<SoapObject>() {
									@Override
									public SoapObject call() throws Exception {
										detail = GetWeatherService
												.getWeatherByCity(city, handler);

										pd = new ParseDetail(detail);
										detailContent = new WeatherDetail();
										detailContent.setContent(pd.getList());
										ShowWeatherView.wd = detailContent;
										return null;
									}
								});
						new Thread(task).start();

					}

				});
	}

	public static AlertDialog.Builder setNegativeButton(
			final AlertDialog.Builder builder, final Context context) {
		// 调用setNegativeButton方法添加取消按钮
		return builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
	}

	public void onBackPressed() {

		if (lastClickTime <= 0) {
			Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
			lastClickTime = System.currentTimeMillis();
		} else {
			long currentClickTime = System.currentTimeMillis();
			if (currentClickTime - lastClickTime < 1500) {
				finish();
			} else {
				Toast.makeText(this, "再按一次后退键退出应用", Toast.LENGTH_SHORT).show();
				lastClickTime = currentClickTime;
			}
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
