package org.arkiwi.app.service;

import java.util.ArrayList;

import org.arkiwi.app.R;
import org.arkiwi.app.activity.ATab;
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.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class FeedBurnIndeterminato extends Service {
	private final static String LOG_TAG = "FeedBurnIndeterminato";
	public final static int NOTIFY_FEEDS_UPDATED = 1;
	private final static int FEEDBURN_NOTIFY_ID = 1;
	private static Intent callBint;
	private NotificationManager notifyManager;	
	private BgFeedBurn bgThread;
	private Notification notification;
	private PendingIntent pIntent;
	private int notificationNumber;
	private boolean toStop;
	
	@Override
	public void onCreate() {
		Log.i(LOG_TAG, "Service FBI Created");
		super.onCreate();
				
		bgThread = new BgFeedBurn();
		bgThread.start();
		
		callBint = new Intent(this, ATab.class);
		callBint.putExtra("feedBurn", NOTIFY_FEEDS_UPDATED);
		pIntent = PendingIntent
				.getActivity(this, 0, callBint, PendingIntent.FLAG_UPDATE_CURRENT);
		
		notifyManager = (NotificationManager) 
				getSystemService(NOTIFICATION_SERVICE);		
		notification = new Notification(
							R.drawable.feedburn_notify,
							getString(R.string.app_feed_notify_title), 
							System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.flags |= Notification.DEFAULT_SOUND;
	}

	public void sendNotification(int[] changed,String title) {
		String msg="Feed:"+title+" :: "
			+getString(R.string.app_feed_notify_new)+changed[Db.STATUS_NEW]
			+getString(R.string.app_feed_notify_del)+changed[Db.STATUS_DELETED]
			+getString(R.string.app_feed_notify_mod)+changed[Db.STATUS_MOD];

		notification.number=++notificationNumber;
		notification.setLatestEventInfo (this, 
				getString(R.string.app_feed_notify_title),
				msg, pIntent);
		
		notifyManager.notify(FEEDBURN_NOTIFY_ID, notification);
	}
	
	private final class BgFeedBurn extends Thread {
		public boolean running = true;
		private DbFeed db;
		private ArrayList<FeedQuery> fq;
		private int[] changed = new int[3];

		public void run() {
			SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(getBaseContext());
			long delay = Long.valueOf(
					prefs.getString(getString(R.string.key_refresh_service), "3600")) * 1000;
		
			while (running) {
				FeedQuery oFeed, nFeed;
				String xml;
				
				fq = new ArrayList<FeedQuery>();
				db = new DbFeed(getApplicationContext());
				db.openW();
				fq = db.fillQuerys(Db.Q_LAST + " DESC");
				
				for (int i = 0; i < fq.size(); i++) {
					oFeed = fq.get(i);
					xml=SNetwork.doGet(oFeed.getLink());
					
					if (xml !=null){
						RssReader rssReader = RssReader.getInstance();
						rssReader.clearFeedQuery();
						rssReader.setFeedQuery(xml);
						
						nFeed = rssReader.getFeedQuery();
					
						if(FeedBurn.refresh(nFeed, oFeed, db, changed)) {
							//rssReader.setDrawed(false);
							db.updateAttrQuery(Db.Q_LAST, nFeed.getLast(), oFeed.getQid());
							if (! toStop)
								sendNotification(changed, nFeed.getTitle());
						}else{
							Log.d(LOG_TAG,"non è cambiato niente per:"+nFeed.getTitle());
						}
					}
				}
				
				db.close();
				fq = null;
				oFeed = null;
				nFeed = null;
				xml=null;
				changed[Db.STATUS_MOD]=0;
				changed[Db.STATUS_NEW]=0;
				changed[Db.STATUS_DELETED]=0;
				
				if (toStop) {
					running = false;
				} else {
					try {
						Log.i(LOG_TAG, "Delay is (ms) " + delay);
						Thread.sleep(delay);
					} catch (InterruptedException ie) {
						Log.d(LOG_TAG,"BgFeedBurn() problemi di sonno");
						ie.getStackTrace();
					}
				}
				
			}

			stopSelf();
		}
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(LOG_TAG, "Service Started");
		toStop = intent.getBooleanExtra("stop", false);
		return super.onStartCommand(intent, flags, startId);
	}

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

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

}
