package service;

import receiver.AutoUpdateReceiver;
import util.HttpCallbackListener;
import util.HttpUtil;
import util.Utility;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;

public class AutoUpdateService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		//¿ªÆôÏ̸߳üÐÂÊý¾Ý£¬ÒòΪÉæ¼°ÁªÍøËùÒÔ¿ªÐÂÏß³Ì
		Thread thread = new Thread(new Runnable(){

			@Override
			public void run() {
				updateWeather();
			}
		});
		thread.start();
		
		//ÉèÖö¨Ê±
		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
		int anHour = 8 * 60 * 1000; //ÉèÖÃ8СʱÒÔºó
		long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
		//¶¨ÒåÒâͼ
		Intent i = new Intent(this , AutoUpdateReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
		//ÉèÖö¨Ê±ÈÎÎñ
		manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
		
		return super.onStartCommand(intent, flags, startId);
		
	}
	
	//¸üÐÂÌìÆøÊý¾Ý
	private void updateWeather() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String weatherCode = prefs.getString("weather_code", "");
		String address = "http://www.weather.com.cn/adat/cityinfo/"+ weatherCode + ".html";
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
			
			@Override
			public void onFinish(String response) {
				if(!TextUtils.isEmpty(response)) {
					//½«Êý¾Ý½øÐнâÎö ,²¢±£´æ
					Utility.handleWeatherResponse(AutoUpdateService.this , response);
				}
			}
			
			@Override
			public void onError(Exception e) {
				e.printStackTrace();
			}
		});
	}
}
