package com.axelby.podax;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Service;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.database.Cursor;
import android.os.Bundle;
import android.os.IBinder;

public class GPodderSyncService extends Service {
    private static final Object _syncAdapterLock = new Object();
    private static GPodderSyncAdapter _syncAdapter = null;

    @Override
    public void onCreate() {
        synchronized (_syncAdapterLock) {
            if (_syncAdapter == null) {
                _syncAdapter = new GPodderSyncAdapter(getApplicationContext(), true);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return _syncAdapter.getSyncAdapterBinder();
    }

	private static class GPodderSyncAdapter extends AbstractThreadedSyncAdapter {
	
		private Context _context;
	
		public GPodderSyncAdapter(Context context, boolean autoInitialize) {
	        super(context, autoInitialize);
	        _context = context;
	    }
	
		@Override
		public void onPerformSync(Account account, Bundle extras, String authority,
				ContentProviderClient provider, SyncResult syncResult) {
			// find the last timestamp
			String[] projection = { SubscriptionProvider.COLUMN_GPODDER_SYNCTIME };
			Cursor c = _context.getContentResolver().query(SubscriptionProvider.URI, projection, null, null, SubscriptionProvider.COLUMN_GPODDER_SYNCTIME + " DESC");
			if (!c.moveToNext())
				return;
			int lastTimestamp = c.getInt(0);
			c.close();

			AccountManager accountManager = AccountManager.get(_context);
			GPodderClient client = new GPodderClient(_context, account.name, accountManager.getPassword(account));
			if (client.authenticate()) {
				client.getSubscriptionChanges(lastTimestamp);
				client.sendSubscriptions();
			}
		}
	
	}
}
@@ -1348,16 +1348,231 @@
 sult) %7B%0A
+%09%09%09AccountManager accountManager = AccountManager.get(_context);%0A%09%09%09GPodderClient client = new GPodderClient(_context, account.name, accountManager.getPassword(account));%0A%09%09%09if (!client.authenticate())%0A%09%09%09%09return;%0A%0A
 %09%09%09// fi
@@ -1587,21 +1587,27 @@
 ast time
-stamp
+ we updated
 %0A%09%09%09Stri
@@ -1925,209 +1925,81 @@
 %0A%09%09%09
-AccountManager accountManager = AccountManager.get(_context);%0A%09%09%09GPodderClient client = new GPodderClient(_context, account.name, accountManager.getPassword(account));%0A%09%09%09if (client.authenticate()) %7B%0A%09
+// update gpodder with new subscriptions%0A%09%09%09client.sendSubscriptions();%0A%0A
 %09%09%09c
@@ -2047,45 +2047,8 @@
 p);%0A
-%09%09%09%09client.sendSubscriptions();%0A%09%09%09%7D%0A
 %09%09%7D%0A

reorder gpodder sync operations