package BWP.MobileSale;

import org.forks.jsonrpc.JsonRpcException;
import org.forks.jsonrpc.RpcFacade;
import BWP.MobileSale.Util.ConfigUtil;
import BWP.MobileSale.Util.StringUtil;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;

public class UpdateService extends Service {

	class CheckUpdateTask extends  AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			try {
				CheckUpdate();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	private void CheckUpdate() throws JsonRpcException {
		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.cancel("MobileSaler", 0);
		if(StringUtil.IsNullOrEmpty(ConfigUtil.getServerUri(this))){
			return;
		}
		
		String method = "/Sale/Sale/Rpcs/MobileSaleClientRpc/GetAndroidClientVerion";
		Long serverVersion = RpcFacade.rpcCall(method);
		if (serverVersion != Utils.CurrentVersion) {
			
			Intent intent = new Intent(this,ClientUpdateActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
			Notification notification = new Notification();
			notification.icon = R.drawable.ic_launcher;
			notification.setLatestEventInfo(this, "管理系统有不同客户端更新,点击下载", 
					String.format("当前:%s,服务器:%s",Utils.CurrentVersion,serverVersion), pendingIntent);
			manager.notify("MobileSaler", 0, notification);	
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		new  CheckUpdateTask().execute();
		return super.onStartCommand(intent, flags, startId);
	}



}
