package org.arkiwi.app.service;

import org.arkiwi.app.database.Db;
import org.arkiwi.app.database.DbFeed;
import org.arkiwi.app.feed.FeedQuery;
import org.arkiwi.app.rss.RssReader;
import org.arkiwi.app.utility.FeedBurn;
import org.arkiwi.app.utility.SNetwork;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class FeedBurnPrecario extends Service {
	private final static String LOG_TAG = "FeedBurnP";
	private FBPThread bgThread;
	private int qid;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		bgThread = new FBPThread();
		bgThread.start();
		
		Log.i(LOG_TAG, "Service Created");
	}

	private final class FBPThread extends Thread {
		private DbFeed db;
		private int[] changed = new int[3];

		public void run() {
			db = new DbFeed(getApplicationContext());
			db.openW();
			if (qid != -1){
				FeedQuery oFeed = db.fillQuery(qid);
				String xml=SNetwork.doGet(oFeed.getLink());
				
				if (xml !=null){
					RssReader rssReader = RssReader.getInstance();
					rssReader.clearFeedQuery();
					rssReader.setFeedQuery(xml);
					
					FeedQuery nFeed = rssReader.getFeedQuery();
					
					if(FeedBurn.refresh(nFeed, oFeed, db, changed)) {
						db.updateAttrQuery(Db.Q_LAST, nFeed.getLast(), qid);
						FeedBurn.vibratorNotification(getBaseContext(), FeedBurn.NEWS);
					}else{
						FeedBurn.vibratorNotification(getBaseContext(), FeedBurn.NO_NEWS);
						Log.d(LOG_TAG,"non è cambiato niente per:"+nFeed.getTitle());
					}
				}
			}
			db.close();
			stopSelf();
		}
	}
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(LOG_TAG, "Service Started");
		qid = intent.getIntExtra("qid", -1);
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(LOG_TAG, "Service Destroyed");
	}

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

}
