package com.coolweather.app.activity;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.coolweather.app.R;
import com.coolweather.app.db.CoolWeatherDB;
import com.coolweather.app.model.City;
import com.coolweather.app.model.County;
import com.coolweather.app.model.Province;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;

public class ChooseAreaActivity extends Activity{
	
	public static final int LEVEL_PROVINCE = 0;
	public static final int LEVEL_CITY = 1;
	public static final int LEVEL_COUNTY = 2;
	
	private ProgressDialog progressDialog;
	private TextView titleText;
	private ListView listView;
	private ArrayAdapter<String> adapter;
	private CoolWeatherDB coolWeatherDB;
	private List<String> dataList=new ArrayList<String>();
	/**
	 *Ê¡ÁÐ±í 
	 */
	private List<Province> provinceList;
	/**
	 *ÊÐÁÐ±í 
	 */
	private List<City> cityList;
	/**
	 *ÏØÁÐ±í 
	 */
	private List<County> countyList;
	/**
	 * Ñ¡ÖÐµÄÊ¡·Ý
	 */
	private Province selectedProvince;
	/**
	 *Ñ¡ÖÐµÄ³ÇÊÐ 
	 */
	private City selectedCity;
	/**
	 *µ±Ç°Ñ¡ÖÐµÄ¼¶±ð 
	 */
	private int currentLevel;
	/**
	 *ÊÇ·ñ´ÓWeatherActivityÖÐÌø×ª¹ýÀ´¡£ 
	 */
	private boolean isFromWeatherActivity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		isFromWeatherActivity=getIntent().getBooleanExtra(
				"from_weather_activity", false);
		
		SharedPreferences prefs = PreferenceManager.
				getDefaultSharedPreferences(this);
		//ÒÑ¾­Ñ¡ÔñÁË³ÇÊÐÇÒ²»ÊÇ´ÓWeatherActivityÌø×ª¹ýÀ´£¬²Å»áÖ±½ÓÌø×ªµ½WeatherActivity
		if(prefs.getBoolean("city_selected", false) && !isFromWeatherActivity){
			Intent intent = new Intent(this,WeatherActivity.class);
			startActivity(intent);
			finish();
			return;
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);
		listView = (ListView)findViewById(R.id.list_view);
		titleText = (TextView)findViewById(R.id.title_text);
		adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
				dataList);
		listView.setAdapter(adapter);
		coolWeatherDB = CoolWeatherDB.getInstance(this);
		listView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int index,
					long arg3) {
				if(currentLevel == LEVEL_PROVINCE){
					selectedProvince = provinceList.get(index);
					queryCities();
				}else if(currentLevel == LEVEL_CITY){
					selectedCity=cityList.get(index);
					queryCounties();
				}else if(currentLevel == LEVEL_COUNTY){
					String countyCode = countyList.get(index).getCountyCode();
					Intent intent = new Intent(ChooseAreaActivity.this,
							WeatherActivity.class);
					intent.putExtra("county_code", countyCode);
					startActivity(intent);
					finish();
				}
			}
			
		});
		queryProvinces();	//¼ÓÔØÊ¡¼¶Êý¾Ý
	}
	
	/**
	 * ²éÑ¯È«¹úËùÓÐµÄÊ¡·Ý£¬ÓÅÏÈ´ÓÊý¾Ý¿â²éÑ¯£¬Èç¹ûÃ»ÓÐ²éÑ¯µ½ÔÙÈ¥·þÎñÆ÷ÉÏ²éÑ¯¡£
	 */
	private void queryProvinces(){
		provinceList = coolWeatherDB.loadProvinces();
		if(provinceList.size() > 0){
			dataList.clear();
			for(Province province : provinceList){
				dataList.add(province.getProvinceName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText("ÖÐ¹ú");
			currentLevel=LEVEL_PROVINCE;
		}else{
			queryFromServer(null, "province");
		}
	}
	
	/**
	 *²éÑ¯Ñ¡ÖÐÊ¡ÄÚËùÓÐµÄÊÐ£¬ÓÅÏÈ´ÓÊý¾Ý¿â²éÑ¯£¬Èç¹ûÃ»ÓÐ²éÑ¯µ½ÔÙÈ¥·þÎñÆ÷ÉÏ²éÑ¯¡£ 
	 */
	private void queryCities(){
		cityList=coolWeatherDB.loadCities(selectedProvince.getId());
		if(cityList.size() > 0){
			dataList.clear();
			for(City city : cityList){
				dataList.add(city.getCityName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectedProvince.getProvinceName());
			currentLevel=LEVEL_CITY;
		}else{
			queryFromServer(selectedProvince.getProvinceCode(),"city");
		}
	}
	
	/**
	 * ²éÑ¯Ñ¡ÖÐÊÐÄÚµÄËùÓÐÏØ£¬ÓÅÏÈ´ÓÊý¾Ý¿â²éÑ¯£¬Èç¹ûÃ»ÓÐ²éÑ¯µ½ÔÙµ½·þÎñÆ÷ÉÏÈ¥²éÑ¯¡£
	 */
	private void queryCounties(){
		countyList=coolWeatherDB.loadCounties(selectedCity.getId());
		if(countyList.size() > 0){
			dataList.clear();
			for(County county : countyList){
				dataList.add(county.getCountyName());
			}
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectedCity.getCityName());
			currentLevel=LEVEL_COUNTY;
		}else{
			queryFromServer(selectedCity.getCityCode(),"county");
		}
	}
	
	/**
	 *¸ù¾Ý´«ÈëµÄ´úºÅºÍÊý¾ÝÀàÐÍ´Ó·þÎñÆ÷ÉÏ²éÑ¯Ê¡ÊÐÏØÊý¾Ý¡£ 
	 */
	private void queryFromServer(final String code,final String type){
		String address;
		if(!TextUtils.isEmpty(code)){
			address="http://www.weather.com.cn/data/list3/city"+code+".xml";
		}else{
			address="http://www.weather.com.cn/data/list3/city.xml";
		}
		showProgressDialog();
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener(){
			@Override
			public void onFinish(String response){
				boolean result=false;
				if("province".equals(type)){
					result=Utility.handleProvincesResponse(coolWeatherDB,
							response);
				}else if("city".equals(type)){
					result=Utility.handleCitiesResponse(coolWeatherDB, 
							response,selectedProvince.getId());
				}else if("county".equals(type)){
					result=Utility.handleCountiesResponse(coolWeatherDB,
							response, selectedCity.getId());
				}
				if(result){
					//Í¨¹ýrunOnThread()·½·¨»Øµ½Ö÷Ïß³Ì´¦ÀíÂß¼­
					runOnUiThread(new Runnable(){
						@Override
						public void run(){
							closeProgressDialog();
							if("province".equals(type)){
								queryProvinces();
							} else if("city".equals(type)){
								queryCities();
							} else if("county".equals(type)){
								queryCounties();
							}
						}
					});
				}
			}
			
			@Override
			public void onError(Exception e){
				//Í¨¹ýrunOnUiThread()·½·¨»Øµ½Ö÷Ïß³Ì´¦ÀíÂß¼­
				runOnUiThread(new Runnable(){
					@Override
					public void run(){
						closeProgressDialog();
						Toast.makeText(ChooseAreaActivity.this,
								"¼ÓÔØÊ§°Ü",Toast.LENGTH_SHORT).show();
					}
				});
			}
			
			
		});
		
	}
	
	/**
	 *ÏÔÊ¾½ø¶È¶Ô»°¿ò 
	 */
	private void showProgressDialog(){
		if(progressDialog == null){
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("ÕýÔÚ¼ÓÔØÖÐ...");
			progressDialog.setCanceledOnTouchOutside(false);
		}
		progressDialog.show();
	}
	
	/**
	 *¹Ø±Õ½ø¶È¶Ô»°¿ò 
	 */
	private void closeProgressDialog(){
		if(progressDialog!=null){
			progressDialog.dismiss();
		}
	}
	
	/**
	 * ²¶»ñBack°´¼ü£¬¸ù¾Ýµ±Ç°¼¶±ðÀ´ÅÐ¶Ï£¬´ËÊ±Ó¦¸Ã·µ»ØÊÐÁÐ±í£¬Ê¡ÁÐ±í£¬»¹ÊÇÖ±½ÓÍË³ö
	 */
	@Override
	public void onBackPressed(){
		if(currentLevel == LEVEL_COUNTY){
			queryCities();
			
		} else if(currentLevel == LEVEL_CITY){
			queryProvinces(); 
		}else{
			
			if(isFromWeatherActivity){
				Intent intent=new Intent(this,WeatherActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}

}
