package de.sebse.fuplanner;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.google.android.material.navigation.NavigationView;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import de.sebse.fuplanner.fragments.CanteensFragment;
import de.sebse.fuplanner.fragments.ModulesFragment;
import de.sebse.fuplanner.fragments.NewsFragment;
import de.sebse.fuplanner.fragments.PrefsFragment;
import de.sebse.fuplanner.fragments.ScheduleFragment;
import de.sebse.fuplanner.fragments.StartupFragment;
import de.sebse.fuplanner.fragments.canteen.DaySwitcherFragment;
import de.sebse.fuplanner.fragments.moddetails.ModDetailFragment;
import de.sebse.fuplanner.services.canteen.CanteenBrowser;
import de.sebse.fuplanner.services.canteen.types.Canteen;
import de.sebse.fuplanner.services.canteen.types.CanteenListener;
import de.sebse.fuplanner.services.fulogin.AccountGeneral;
import de.sebse.fuplanner.services.kvv.KVV;
import de.sebse.fuplanner.services.kvv.KVVListener;
import de.sebse.fuplanner.services.kvv.sync.KVVContentProvider;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.services.kvv.types.Modules;
import de.sebse.fuplanner.services.news.NewsManager;
import de.sebse.fuplanner.tools.CustomAccountManager;
import de.sebse.fuplanner.tools.CustomNotificationManager;
import de.sebse.fuplanner.tools.MainActivityListener;
import de.sebse.fuplanner.tools.NewAsyncQueue;
import de.sebse.fuplanner.tools.Preferences;
import de.sebse.fuplanner.tools.Regex;
import de.sebse.fuplanner.tools.RequestPermissionsResultListener;
import de.sebse.fuplanner.tools.logging.Logger;
import de.sebse.fuplanner.tools.types.News;

public class MainActivity extends AppCompatActivity
        implements MainActivityListener, KVVListener, CanteenListener,
        NavigationView.OnNavigationItemSelectedListener,
        ModulesFragment.OnModulesFragmentInteractionListener,
        CanteensFragment.OnCanteensFragmentInteractionListener {

    private static final int FRAGMENT_NONE = -1;
    private static final int FRAGMENT_STARTUP = 0;
    private static final int FRAGMENT_MODULES = 1;
    private static final int FRAGMENT_MODULES_DETAILS = 2;
    private static final int FRAGMENT_SCHEDULE = 4;
    private static final int FRAGMENT_CANTEENS = 5;
    private static final int FRAGMENT_CANTEENS_DETAILS = 6;
    private static final int FRAGMENT_PREFERENCES = 7;
    private static final int FRAGMENT_NEWS = 8;

    private static final String ARG_FRAGMENT_PAGE = "fragment_page";
    private static final String ARG_FRAGMENT_STATUS = "fragment_status";
    private static final int DOUBLE_CLICK_TO_EXIT_MILLIS = 2000;

    private FragmentManager mFragmentManager;
    private KVV mKVV;
    private NewsManager mNewsManager;
    private CanteenBrowser mCanteenBrowser;
    private final Logger log = new Logger(this);
    private NavigationView mNavigationView;

    private int mFragmentPage = FRAGMENT_NONE;
    @NotNull
    private String mFragmentData = "";
    private final HashMap<String, RequestPermissionsResultListener> permissionListeners = new HashMap<>();
    private final NewAsyncQueue mQueue = new NewAsyncQueue();
    private long mDoubleBackToExitPressedOnce = 0;
    private CustomAccountManager mAccountManager;
    private boolean isPaused = false;
    private boolean isLoggedInBeforePause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAccountManager = new CustomAccountManager(AccountManager.get(this), () -> MainActivity.this);
        int desiredPage = getDefaultFragmentAfterLogin();
        String desiredData = "";
        if (savedInstanceState != null) {
            desiredPage = savedInstanceState.getInt(ARG_FRAGMENT_PAGE, desiredPage);
            desiredData = savedInstanceState.getString(ARG_FRAGMENT_STATUS, desiredData);
        }

        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        mNavigationView = findViewById(R.id.nav_view);
        mNavigationView.setNavigationItemSelectedListener(this);
        mFragmentManager = getSupportFragmentManager();

        //if (mAccountManager.getAccountsByType(AccountGeneral.ACCOUNT_TYPE).length == 0) {
        if (!mAccountManager.hasAccounts(AccountGeneral.ACCOUNT_TYPE)) {
            desiredPage = getDefaultFragmentAfterLogout();
            desiredData = "";
            mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
            updateNavigation();
            changeFragment(desiredPage, desiredData);
        } else {
            updateNavigation();
            changeFragment(FRAGMENT_STARTUP);
            int targetPage = desiredPage;
            String targetData = desiredData;
            getKVV().account().restoreOnlineLogin(isRestored -> {
                updateNavigation();
                if (isRestored)
                    changeFragment(targetPage, targetData);
                else
                    changeFragment(getDefaultFragmentAfterLogout());
            });
        }

        if (!Preferences.getBoolean(this, R.string.pref_set_auto_sync_on_startup)) {
            registerSync();
            Preferences.setBoolean(this, R.string.pref_set_auto_sync_on_startup, true);
        }
        CustomNotificationManager.createNotificationChannel(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPaused = true;
        isLoggedInBeforePause = getKVV().account().isLoggedIn();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPaused) {
            getKVV().account().restoreOnlineLogin(isRestored -> {
                updateNavigation();
                if (isRestored && !isLoggedInBeforePause)
                    changeFragment(getDefaultFragmentAfterLogin());
                else if (!isRestored && isLoggedInBeforePause) {
                    getKVV().account().logout(false);
                    changeFragment(getDefaultFragmentAfterLogout());
                }
            });
            getKVV().modules().list().reloadIfOutdated();
        }
        isPaused = false;
    }

    @Override
    public void onBackPressed() {
        if (mDoubleBackToExitPressedOnce + DOUBLE_CLICK_TO_EXIT_MILLIS > System.currentTimeMillis()) {
            super.onBackPressed();
            return;
        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (mFragmentPage == FRAGMENT_MODULES_DETAILS) {
                ModDetailFragment fragment = (ModDetailFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_MODULES_DETAILS));
                if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
                    fragment.gotoFragmentPart(0, -1);
                } else {
                    changeFragment(FRAGMENT_MODULES);
                }
            } else if (mFragmentPage == FRAGMENT_CANTEENS_DETAILS) {
                DaySwitcherFragment fragment = (DaySwitcherFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_CANTEENS_DETAILS));
                if (fragment != null && fragment.isVisible() && Regex.has("\\.[1-9][0-9]*", fragment.getData())) {
                    fragment.gotoFragmentPart(0);
                } else {
                    changeFragment(FRAGMENT_CANTEENS);
                }
            } else if (getKVV().account().isLoggedIn() && mFragmentPage != getDefaultFragmentAfterLogin()) {
                changeFragment(getDefaultFragmentAfterLogin());
            } else {
                mDoubleBackToExitPressedOnce = System.currentTimeMillis();
                showToast(R.string.back_to_exit);
                //getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if (mFragmentPage == FRAGMENT_SCHEDULE) {
            getMenuInflater().inflate(R.menu.options_schedule, menu);
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.refresh) {
            ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
            if (fragment != null && fragment.isVisible()) {
                fragment.invalidate(true);
            }
            return true;
        } else if (id == R.id.go_to_today) {
            ScheduleFragment fragment = (ScheduleFragment) mFragmentManager.findFragmentByTag(String.valueOf(FRAGMENT_SCHEDULE));
            if (fragment != null && fragment.isVisible()) {
                fragment.goToToday();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id) {
            case R.id.nav_modules:
                changeFragment(FRAGMENT_MODULES);
                break;
            case R.id.nav_schedule:
                changeFragment(FRAGMENT_SCHEDULE);
                break;
            case R.id.nav_canteens:
                changeFragment(FRAGMENT_CANTEENS);
                break;
            case R.id.nav_news:
                changeFragment(FRAGMENT_NEWS);
                break;
            case R.id.nav_settings:
                changeFragment(FRAGMENT_PREFERENCES);
                break;
            case R.id.nav_share:
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.share_intent, getResources().getString(R.string.app_url)));
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
                break;
            case R.id.nav_logout:
                getKVV().account().logout(true);
                getKVV().modules().list().delete();
                break;

        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

        int size = mNavigationView.getMenu().size();
        for (int k = 0; k < size; k++) {
            mNavigationView.getMenu().getItem(k).setChecked(mNavigationView.getMenu().getItem(k) == item);
        }
        item.setChecked(true);

        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        if (mFragmentPage != FRAGMENT_STARTUP && mFragmentPage != FRAGMENT_NONE) {
            Fragment fragment = mFragmentManager.findFragmentByTag(String.valueOf(mFragmentPage));
            savedInstanceState.putInt(ARG_FRAGMENT_PAGE, mFragmentPage);
            if (fragment instanceof ModDetailFragment) {
                savedInstanceState.putString(ARG_FRAGMENT_STATUS, ((ModDetailFragment) fragment).getData());
            } else if (fragment instanceof DaySwitcherFragment) {
                savedInstanceState.putString(ARG_FRAGMENT_STATUS, ((DaySwitcherFragment) fragment).getData());
            } else {
                savedInstanceState.putString(ARG_FRAGMENT_STATUS, mFragmentData);
            }
        }
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        for (RequestPermissionsResultListener listener: permissionListeners.values()) {
            listener.callback(requestCode, permissions, grantResults);
        }
    }

    /* --------------------------------------------*/
    /* --------------------------------------------*/
    /* --------------------------------------------*/

    public NewsManager getNewsManager() {
        if (this.mNewsManager == null) {
            this.mNewsManager = new NewsManager(this);
        }
        return this.mNewsManager;
    }

    public KVV getKVV() {
        if (this.mKVV == null) {
            this.mKVV = new KVV(this, this);
        }
        return this.mKVV;
    }

    public CanteenBrowser getCanteenBrowser() {
        if (this.mCanteenBrowser == null) {
            this.mCanteenBrowser = new CanteenBrowser(this);
        }
        return this.mCanteenBrowser;
    }

    private int getDefaultFragmentAfterLogin() {
        return FRAGMENT_MODULES;
    }

    private int getDefaultFragmentAfterLogout() {
        return FRAGMENT_CANTEENS;
    }

    private void toLogoutState() {
        setRefreshFailedBanner(false);
        updateNavigation();
        changeFragment(getDefaultFragmentAfterLogout());
        mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
    }

    private void toLoginState(String fullName, String email, int newFragment) {
        updateNavigation();

        View header = mNavigationView.getHeaderView(0);
        ((TextView) header.findViewById(R.id.login_name)).setText(fullName);
        ((TextView) header.findViewById(R.id.login_mail)).setText(email);

        changeFragment(newFragment);
        registerSync();
    }

    private void registerSync() {
        Account accountByType = mAccountManager.getAccountByType(AccountGeneral.ACCOUNT_TYPE);
        if (accountByType != null) {
            ContentResolver.setSyncAutomatically(accountByType, KVVContentProvider.PROVIDER_NAME, true);
            ContentResolver.addPeriodicSync(
                accountByType,
                KVVContentProvider.PROVIDER_NAME,
                Bundle.EMPTY,
                AccountGeneral.SYNC_INTERVAL);
        }
    }

    private void changeFragment(int newFragment) {
        changeFragment(newFragment, "");
    }

    private void changeFragment(int newFragment, String newData) {
        if (mFragmentManager.isStateSaved())
            return;
        if (newFragment == FRAGMENT_CANTEENS_DETAILS && newData.equals(""))
            newFragment = FRAGMENT_CANTEENS;
        if (newFragment == FRAGMENT_MODULES_DETAILS && newData.equals(""))
            newFragment = FRAGMENT_MODULES;

        onTitleTextChange(R.string.app_name);
        Fragment fragment;
        switch (newFragment) {
            case FRAGMENT_MODULES_DETAILS:
                fragment = ModDetailFragment.newInstance(newData);
                break;
            case FRAGMENT_MODULES:
                fragment = ModulesFragment.newInstance();
                break;
            /*case FRAGMENT_LOGIN:
                fragment = LoginFragment.newInstance();
                break;*/
            case FRAGMENT_SCHEDULE:
                fragment = ScheduleFragment.newInstance();
                break;
            case FRAGMENT_CANTEENS_DETAILS:
                fragment = DaySwitcherFragment.newInstance(newData);
                break;
            case FRAGMENT_CANTEENS:
                fragment = CanteensFragment.newInstance();
                break;
            case FRAGMENT_NEWS:
                Preferences.setLong(this, R.string.pref_last_visited_news, System.currentTimeMillis());
                updateNavigation();
                fragment = NewsFragment.newInstance();
                break;
            case FRAGMENT_PREFERENCES:
                fragment = PrefsFragment.newInstance();
                break;
            default:  // FRAGMENT_STARTUP
                fragment = StartupFragment.newInstance();
                break;
        }

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragcontainer, fragment, String.valueOf(newFragment));
        fragmentTransaction.commit();

        if (newFragment == FRAGMENT_STARTUP) {
            findViewById(R.id.app_bar_include).setVisibility(View.GONE);
        } else {
            findViewById(R.id.app_bar_include).setVisibility(View.VISIBLE);
        }

        this.mFragmentPage = newFragment;
        this.mFragmentData = newData;

        invalidateOptionsMenu();
    }

    private void setRefreshFailedBanner(boolean refreshFailed) {
        View viewNoConnection = findViewById(R.id.no_connection_msg);
        if (refreshFailed)
            viewNoConnection.setVisibility(View.VISIBLE);
        else
            viewNoConnection.setVisibility(View.GONE);
    }

    private void setNavigationSelection() {
        MenuItem item = null;
        switch (mFragmentPage) {
            case FRAGMENT_MODULES_DETAILS:
                getKVV().modules().list().find(mFragmentData, success -> {
                    int size = mNavigationView.getMenu().size();
                    //noinspection ConstantConditions
                    String title = success == null ? null : success.title;
                    for (int k = 0; k < size; k++) {
                        MenuItem menuItem = mNavigationView.getMenu().getItem(k);
                        if (menuItem.getTitle().equals(title)) {
                            menuItem.setChecked(true);
                            break;
                        }
                    }
                }, log::e);
                return;
            case FRAGMENT_MODULES:
                item = mNavigationView.getMenu().findItem(R.id.nav_modules);
                break;
            case FRAGMENT_SCHEDULE:
                item = mNavigationView.getMenu().findItem(R.id.nav_schedule);
                break;
            case FRAGMENT_CANTEENS_DETAILS:
                getCanteenBrowser().getCanteens(success -> {
                    int size = mNavigationView.getMenu().size();
                    Canteen canteen = success.getCanteen(Integer.parseInt(mFragmentData));
                    //noinspection ConstantConditions
                    String title = canteen == null ? null : canteen.getName();
                    for (int k = 0; k < size; k++) {
                        MenuItem menuItem = mNavigationView.getMenu().getItem(k);
                        if (menuItem.getTitle().equals(title)) {
                            menuItem.setChecked(true);
                            break;
                        }
                    }
                }, log::e);
                return;
            case FRAGMENT_CANTEENS:
                item = mNavigationView.getMenu().findItem(R.id.nav_canteens);
                break;
            case FRAGMENT_NEWS:
                item = mNavigationView.getMenu().findItem(R.id.nav_news);
                break;
            case FRAGMENT_PREFERENCES:
                item = mNavigationView.getMenu().findItem(R.id.nav_settings);
                break;
            default:  // FRAGMENT_STARTUP / FRAGMENT_LOGIN
                break;
        }
        if (item != null)
            item.setChecked(true);
    }

    private void setNavigationHeader(boolean isLoggedIn) {
        View header = mNavigationView.getHeaderView(0);
        int login = isLoggedIn ? View.VISIBLE : View.GONE;
        int btn = !isLoggedIn ? View.VISIBLE : View.GONE;

        header.findViewById(R.id.login_name).setVisibility(login);
        header.findViewById(R.id.login_mail).setVisibility(login);
        View viewBtn = header.findViewById(R.id.btn_login_page);
        viewBtn.setVisibility(btn);
        if (!viewBtn.hasOnClickListeners())
            viewBtn.setOnClickListener(v -> {
                DrawerLayout drawer = findViewById(R.id.drawer_layout);
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                }
                mAccountManager.getTokenByType(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_KVV, null);
            });
    }

    private void afterAnyMenuInflate(boolean isLoggedIn, Runnable done) {
        int MAX_COUNT = isLoggedIn ? 3 : 2;
        final int[] count = {0};
        if (isLoggedIn) {
            getKVV().modules().list().recv(success -> {
                int i = 0;
                for (Iterator<Modules.Module> it = success.latestSemesterIterator(); it.hasNext(); ) {
                    Modules.Module module = it.next();
                    MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 101 + i, module.title);
                    menuItem.setOnMenuItemClickListener(item -> {
                        onModulesFragmentInteraction(module.getID());
                        return false;
                    });
                    i++;
                }
                if (++count[0] == MAX_COUNT) done.run();
            }, error -> {
                if (++count[0] == MAX_COUNT) done.run();
                log.e(error);
            });
        }
        getCanteenBrowser().getCanteens(success -> {
            int i = 0;
            for (Canteen canteen: success) {
                MenuItem menuItem = mNavigationView.getMenu().add(Menu.NONE, Menu.NONE, 201 + i, canteen.getName());
                menuItem.setOnMenuItemClickListener(item -> {
                    onCanteensFragmentInteraction(canteen.getId());
                    return false;
                });
                i++;
            }
            if (++count[0] == MAX_COUNT) done.run();
        }, error -> {
            if (++count[0] == MAX_COUNT) done.run();
            log.e(error);
        });
        getNewsManager().recv(success -> {
            long lastVisited = Preferences.getLong(this, R.string.pref_last_visited_news);
            int i = 0;
            for (News news: success) {
                if (news.getDate() > lastVisited) i++;
            }
            if (i > 0) {
                MenuItem menuItem = mNavigationView.getMenu().findItem(R.id.nav_news);
                menuItem.setIcon(R.drawable.ic_sms_failed);
                View view = View.inflate(this, R.layout.action_icon_number, null);
                TextView v = view.findViewById(R.id.number);
                v.setText(String.format(Locale.getDefault(), "%d", i));
                menuItem.setActionView(view);
            }
            if (++count[0] == MAX_COUNT) done.run();
        }, error -> {
            if (++count[0] == MAX_COUNT) done.run();
            log.e(error);
        });
    }

    private void updateNavigation() {
        mQueue.add(() -> {
            boolean isLoggedIn = getKVV().account().isLoggedIn();
            setNavigationHeader(isLoggedIn);
            mNavigationView.getMenu().clear();
            if (isLoggedIn)
                mNavigationView.inflateMenu(R.menu.activity_main_drawer_login);
            else
                mNavigationView.inflateMenu(R.menu.activity_main_drawer);
            afterAnyMenuInflate(isLoggedIn, () -> {
                setNavigationSelection();
                mQueue.next();
            });
        });
    }












    @Override
    public void onModulesFragmentInteraction(final String itemID) {
        changeFragment(FRAGMENT_MODULES_DETAILS, itemID);
        setNavigationSelection();
    }

    @Override
    public void onCanteensFragmentInteraction(final int itemID) {
        changeFragment(FRAGMENT_CANTEENS_DETAILS, String.valueOf(itemID));
        setNavigationSelection();
    }

    @Override
    public void onTitleTextChange(String newTitle) {
        setTitle(newTitle);
    }

    @Override
    public void onTitleTextChange(@StringRes int titleId) {
        setTitle(titleId);
    }

    @Override
    public void onCanteenRefreshCompleted(boolean isFailed) {
        setRefreshFailedBanner(isFailed);
    }

    @Override
    public void addRequestPermissionsResultListener(RequestPermissionsResultListener listener, String id) {
        permissionListeners.put(id, listener);
    }

    @Override
    public void removeRequestPermissionsResultListener(String id) {
        permissionListeners.remove(id);
    }

    @Override
    public void showToast(@StringRes int msgStringRes) {
        showToast(getString(msgStringRes));
    }

    @Override
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }











    @Override
    public void onLogin(LoginToken token) {
        toLoginState(token.getFullName(), token.getEmail(), getDefaultFragmentAfterLogin());
    }

    @Override
    public void onLogout() {
        toLogoutState();
    }

    @Override
    public void onModuleListChange() {
        updateNavigation();
    }

    @Override
    public void onKVVNetworkResponse(NetworkResponse error) {
        setRefreshFailedBanner(error != null);
    }

    @Override
    public CustomAccountManager getAccountManager() {
        return mAccountManager;
    }
}
