/*
 * Copyright (C) 2012 Brian Muramatsu
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.btmura.android.reddit.content;

import java.util.Arrays;
import java.util.Comparator;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.btmura.android.reddit.BuildConfig;
import com.btmura.android.reddit.accounts.AccountAuthenticator;
import com.btmura.android.reddit.accounts.AccountPreferences;
import com.btmura.android.reddit.content.AccountLoader.AccountResult;
import com.btmura.android.reddit.database.Subreddits;

public class AccountLoader extends AsyncTaskLoader<AccountResult> implements
        OnAccountsUpdateListener {

    public static final String TAG = "AccountLoader";

    public static class AccountResult {
        public String[] accountNames;
        public SharedPreferences prefs;

        private AccountResult(String[] accountNames, SharedPreferences prefs) {
            this.accountNames = accountNames;
            this.prefs = prefs;
        }

        public String getLastAccount() {
            String accountName = AccountPreferences.getLastAccount(prefs, Subreddits.ACCOUNT_NONE);
            for (int i = 0; i < accountNames.length; i++) {
                if (accountNames[i].equals(accountName)) {
                    return accountName;
                }
            }
            return accountNames[0];
        }

        // TODO: Get rid of these methods since they are just wrappers.

        public int getLastMessageFilter() {
            return AccountPreferences.getLastMessageFilter(prefs, 0);
        }

        public int getLastProfileFilter() {
            return AccountPreferences.getLastProfileFilter(prefs, 0);
        }

        public int getLastSubredditFilter() {
            return AccountPreferences.getLastSubredditFilter(prefs, 0);
        }
    }

    private static Comparator<Account> ACCOUNT_COMPARATOR = new Comparator<Account>() {
        public int compare(Account lhs, Account rhs) {
            return lhs.name.compareToIgnoreCase(rhs.name);
        }
    };

    private SharedPreferences prefs;
    private AccountManager manager;
    private boolean includeNoAccount;

    private AccountResult result;

    public AccountLoader(Context context, boolean includeNoAccount) {
        super(context);
        this.prefs = AccountPreferences.getPreferences(context);
        this.manager = AccountManager.get(getContext());
        this.manager.addOnAccountsUpdatedListener(this, null, false);
        this.includeNoAccount = includeNoAccount;
    }

    @Override
    public AccountResult loadInBackground() {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "loadInBackground");
        }

        Context context = getContext();

        // Get the accounts and sort them.
        Account[] accounts = manager
                .getAccountsByType(AccountAuthenticator.getAccountType(context));
        Arrays.sort(accounts, ACCOUNT_COMPARATOR);

        // Convert to strings and prepend the no account at the top.
        int start = 0;
        int length = accounts.length;
        if (includeNoAccount) {
            start++;
            length++;
        }
        String[] accountNames = new String[length];
        if (includeNoAccount) {
            accountNames[0] = Subreddits.ACCOUNT_NONE;
        }
        for (int i = 0; i < accounts.length; i++) {
            accountNames[start++] = accounts[i].name;
        }

        // Get a preference to make sure the loading thread is done.
        AccountPreferences.getLastAccount(prefs, null);

        return new AccountResult(accountNames, prefs);
    }

    @Override
    public void deliverResult(AccountResult newResult) {
        if (isReset()) {
            return;
        }

        this.result = newResult;

        if (isStarted()) {
            super.deliverResult(newResult);
        }
    }

    @Override
    protected void onStartLoading() {
        if (result != null) {
            deliverResult(result);
        }
        if (takeContentChanged() || result == null) {
            forceLoad();
        }
    }

    @Override
    protected void onReset() {
        super.onReset();
        onStopLoading();
        result = null;
    }

    public void onAccountsUpdated(Account[] accounts) {
        onContentChanged();
    }
}

@@ -2881,16 +2881,50 @@
 ccount;%0A
+    private boolean listenerAdded;
 %0A    pri
@@ -3171,78 +3171,8 @@
 ));%0A
-        this.manager.addOnAccountsUpdatedListener(this, null, false);%0A
     
@@ -4664,32 +4664,175 @@
 ult);%0A        %7D%0A
+        if (!listenerAdded) %7B%0A            manager.addOnAccountsUpdatedListener(this, null, false);%0A            listenerAdded = true;%0A        %7D%0A
         if (take
@@ -5029,16 +5029,149 @@
 = null;%0A
+        if (listenerAdded) %7B%0A            manager.removeOnAccountsUpdatedListener(this);%0A            listenerAdded = false;%0A        %7D%0A
     %7D%0A%0A 

Add and remove account listener properly