/*
 * 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.app;

import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.content.ContentResolver;
import android.content.Loader;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.btmura.android.reddit.BuildConfig;
import com.btmura.android.reddit.R;
import com.btmura.android.reddit.accounts.AccountPreferences;
import com.btmura.android.reddit.accounts.AccountUtils;
import com.btmura.android.reddit.content.AccountLoader.AccountResult;
import com.btmura.android.reddit.provider.AccountProvider;
import com.btmura.android.reddit.widget.AccountSpinnerAdapter;

public class BrowserActivity extends AbstractBrowserActivity implements OnNavigationListener,
        AccountNameHolder {

    public static final String EXTRA_SUBREDDIT_NAME = "sn";

    private AccountSpinnerAdapter adapter;
    private SharedPreferences prefs;

    @Override
    protected void setContentView() {
        setContentView(R.layout.browser);
    }

    @Override
    protected boolean skipSetup() {
        if (isSinglePane && getIntent().hasExtra(EXTRA_SUBREDDIT_NAME)) {
            String name = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
            selectSubredditSinglePane(name, ThingListActivity.FLAG_INSERT_HOME);
            finish();
            return true;
        }
        return false;
    }

    @Override
    protected void setupViews() {
    }

    @Override
    protected void setupActionBar(Bundle savedInstanceState) {
        adapter = new AccountSpinnerAdapter(this, !isSinglePane);
        bar.setDisplayShowTitleEnabled(false);
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        bar.setListNavigationCallbacks(adapter, this);
    }

    @Override
    public void onLoadFinished(Loader<AccountResult> loader, AccountResult result) {
        prefs = result.prefs;
        adapter.setAccountNames(result.accountNames);

        String accountName = result.getLastAccount();
        adapter.setAccountName(accountName);
        adapter.setFilter(result.getLastSubredditFilter());

        int index = adapter.findAccountName(accountName);
        bar.setSelectedNavigationItem(index);
    }

    @Override
    public void onLoaderReset(Loader<AccountResult> loader) {
        adapter.setAccountNames(null);
    }

    @Override
    public String getAccountName() {
        return adapter.getAccountName();
    }

    @Override
    protected int getFilter() {
        return adapter.getFilter();
    }

    @Override
    protected boolean hasSubredditList() {
        return true;
    }

    @Override
    protected void refreshActionBar(String subreddit, Bundle thingBundle) {
        bar.setDisplayHomeAsUpEnabled(thingBundle != null);
        adapter.setSubreddit(subreddit);
    }

    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        adapter.updateState(itemPosition);

        String accountName = adapter.getAccountName();
        AccountPreferences.setLastAccount(prefs, accountName);

        int filter = adapter.getFilter();
        AccountPreferences.setLastSubredditFilter(prefs, filter);

        if (BuildConfig.DEBUG) {
            Log.d(TAG, "onNavigationItemSelected i:" + itemPosition
                    + " an:" + accountName + " f:" + filter);
        }

        // Quickly sync to check whether the user has new messages.
        if (AccountUtils.isAccount(accountName)) {
            ContentResolver.requestSync(AccountUtils.getAccount(this, accountName),
                    AccountProvider.AUTHORITY, Bundle.EMPTY);
        }

        SubredditListFragment slf = getSubredditListFragment();
        ThingListFragment tlf = getThingListFragment();
        if (slf == null || !slf.getAccountName().equals(accountName)) {
            String name = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME);
            String subreddit;
            if (!isSinglePane && !TextUtils.isEmpty(name)) {
                subreddit = name;
            } else {
                subreddit = AccountPreferences.getLastSubreddit(prefs, accountName);
            }
            setSubredditListNavigation(subreddit, null);
        } else if (tlf != null && tlf.getFilter() != filter) {
            replaceThingListFragmentMultiPane();
        }

        // Invalidate menu so that mail icon disappears when switching back to
        // app storage account.
        invalidateOptionsMenu();

        return true;
    }

    @Override
    public void onSubredditSelected(String subreddit) {
        super.onSubredditSelected(subreddit);
        AccountPreferences.setLastSubreddit(prefs, getAccountName(), subreddit);
    }
}

@@ -638,16 +638,49 @@
 t.app;%0A%0A
+import android.accounts.Account;%0A
 import a
@@ -861,24 +861,53 @@
 references;%0A
+import android.os.AsyncTask;%0A
 import andro
@@ -3642,32 +3642,38 @@
 tion);%0A%0A        
+final 
 String accountNa
@@ -4185,36 +4185,214 @@
     
-ContentResolver.requestSync(
+// requestSync can trigger a strict mode warning by writing to disk.%0A            AsyncTask.SERIAL_EXECUTOR.execute(new Runnable() %7B%0A                public void run() %7B%0A                    Account account = 
 Acco
@@ -4411,20 +4411,39 @@
 Account(
-this
+getApplicationContext()
 , accoun
@@ -4448,17 +4448,17 @@
 untName)
-,
+;
 %0A       
@@ -4461,32 +4461,69 @@
                 
+ ContentResolver.requestSync(account,
  AccountProvider
@@ -4549,16 +4549,50 @@
 EMPTY);%0A
+                %7D%0A            %7D);%0A
         

Fix strict mode warning for requesting sync