/*
 * DSBDirect
 * Copyright (C) 2019 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * This software is not affiliated with heinekingmedia GmbH, the
 * developer of the DSB platform.
 */

package godau.fynn.dsbdirect.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.*;
import android.webkit.WebView;
import android.widget.*;
import com.ortiz.touchview.TouchImageView;
import com.wefika.horizontalpicker.HorizontalPicker;
import godau.fynn.dsbdirect.BuildConfig;
import godau.fynn.dsbdirect.R;
import godau.fynn.dsbdirect.Utility;
import godau.fynn.dsbdirect.manager.DownloadManager;
import godau.fynn.dsbdirect.manager.FileManager;
import godau.fynn.dsbdirect.table.Adapter;
import godau.fynn.dsbdirect.table.Entry;
import godau.fynn.dsbdirect.table.Table;
import godau.fynn.dsbdirect.table.reader.Reader;
import godau.fynn.dsbdirect.table.reader.ReaderRunnable;
import humanize.Humanize;
import humanize.time.TimeMillis;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_LOGIN = 1;

    private Table mCurrentTable;
    private String credentialsId;
    private String credentialsPass;

    private Table[] mTables;
    private Date mTimetabledate;

    private boolean mTimetabledateDisplayed = false;

    private Utility u;
    private FileManager mFileManager;
    private DownloadManager mDownloadManager;

    private ArrayList<Thread> mReaderThreads = new ArrayList<>();

    private TextView mTextView;

    private WebView mWebView;

    private Adapter mAdapter;

    private boolean mParse = true;
    private boolean mMerge = true;

    private Menu mMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        u = new Utility(MainActivity.this);
        u.stylize();

        long drawTimeStart = System.currentTimeMillis();

        setContentView(R.layout.activity_main);

        // Style horizontal picker
        ((HorizontalPicker) findViewById(R.id.page)).setBackgroundColor(u.getColorPrimary());

        long drawTimeEnd = System.currentTimeMillis();
        Log.d("DRAW", "rendering layout took " + (drawTimeEnd - drawTimeStart) + " milliseconds");

        final SharedPreferences sharedPreferences = u.getSharedPreferences();
        credentialsId = sharedPreferences.getString("id", "");
        credentialsPass = sharedPreferences.getString("pass", "");

        mParse = sharedPreferences.getBoolean("parse", true);
        mMerge = sharedPreferences.getBoolean("merge", true);


        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundColor(u.getColorPrimary());
        setSupportActionBar(toolbar);

        setOverflowButtonColor(this, getResources().getColor(R.color.white));

        mTextView = findViewById(R.id.text);

        // Get managers
        mFileManager = new FileManager(MainActivity.this);
        mDownloadManager = new DownloadManager(this);

        int previousVersion = sharedPreferences.getInt("version", BuildConfig.VERSION_CODE);

        // Migrate 1.8.1 (version code 13) users to avoid login screen
        if (previousVersion <= 13) {
            sharedPreferences.edit().putBoolean("login", true).apply();
        }

        // Migrate Röntgen users from 2.0.3 (version code 17)
        if ((previousVersion <= 17) && (credentialsId.equals("219261") || u.getParserUserSetting().equals(Utility.ROENTGEN))) {
            sharedPreferences.edit()
                    .putBoolean("login", false)
                    .putInt("version", BuildConfig.VERSION_CODE)
                    .remove("parser")
                    .apply();

            new AlertDialog.Builder(MainActivity.this)
                    .setTitle(R.string.migrate_roentgen_title)
                    .setMessage(R.string.migrate_roentgen_message)
                    .setCancelable(false)
                    .setNeutralButton(R.string.contact_app_developer, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SettingsActivity.emailTheDev(MainActivity.this);
                            finish();
                        }
                    })
                    .setPositiveButton(R.string.action_reauth, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Login required
                            Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                            startActivityForResult(loginIntent, REQUEST_LOGIN);
                        }
                    })
                    .show();

            // Don't load further
            return;
        }

        // Delete useless auth token from versions from 2.4.1 (version code 22)
        if (previousVersion <= 22) {
            sharedPreferences.edit().remove("token").apply();
        }

        // Start loading or show login screen
        boolean login = sharedPreferences.getBoolean("login", false);
        if (login && !credentialsId.isEmpty() && !credentialsPass.isEmpty()) {
            // Start loading
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getTimetables();
                }
            }).start();
        } else {
            // Login required
            Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
            startActivityForResult(loginIntent, REQUEST_LOGIN);
        }


        // Update checker
        if (u.shouldCheckForUpdates()) {
            u.checkForUpdate(false, mDownloadManager);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            u.schedulePolling();
        }

        // Save version code for potential What's new stuff or migrations
        sharedPreferences.edit().putInt("version", BuildConfig.VERSION_CODE).apply();
    }

    private void networkErrorToUi(Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Snackbar
                        .make(findViewById(R.id.root),
                                getString(R.string.you_are_offline),
                                Snackbar.LENGTH_SHORT)
                        .show();
                // Enter offline mode
                offlineMode();

            }
        });

        e.printStackTrace();
    }

    private void getTimetables() {

        try {
            final JSONArray json = mDownloadManager.downloadTimetableList(credentialsId, credentialsPass);

            // Parse JSON
            mTables = Reader.readTableList(json);


            // Find out whether all tables might be parsable
            boolean findAllHtml = true;
            for (Table table : mTables) {
                if (!table.isHtml()) {
                    findAllHtml = false;
                    break;
                }
            }

            final boolean allHtml = findAllHtml;

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    mTextView.setText(getString(R.string.timetable_uri_acquired));

                    // Find date
                    mTimetabledate = mTables[0].getPublishedDate();


                    if (mMerge && mParse && allHtml) {
                        // All tables can be displayed at once
                        displayMultipleHtmlTimetables(new ArrayList<>(Arrays.asList(mTables)));

                        // Ensure pagePicker is gone
                        findViewById(R.id.page).setVisibility(View.GONE);
                    } else {
                        // Every table has to be displayed separately
                        // Display the first table
                        mCurrentTable = mTables[0];
                        displayTimetable(mTables[0]);

                        // Let user view other tables if necessary
                        if (mTables.length > 1) {
                            HorizontalPicker pagePicker = findViewById(R.id.page);
                            pagePicker.setVisibility(View.VISIBLE);

                            // Display table titles as values in horizontal picker
                            String[] titles = new String[mTables.length];
                            for (int i = 0; i < mTables.length; i++) {
                                titles[i] = mTables[i].getTitle();
                            }
                            pagePicker.setValues(titles);

                            pagePicker.setOnItemSelectedListener(new HorizontalPicker.OnItemSelected() {
                                @Override
                                public void onItemSelected(int index) {
                                    displayTimetable(mTables[index]);
                                }
                            });

                            pagePicker.setOnItemClickedListener(new HorizontalPicker.OnItemClicked() {
                                @Override
                                public void onItemClicked(int index) {
                                    displayTimetabledate(R.string.timetable_published, mTables[index].getPublishedDate());
                                }
                            });
                        }
                    }
                }
            });


        } catch (DownloadManager.UnexpectedResponseException | JSONException e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTextView.setText(R.string.network_invalid_response);
                }
            });
            e.printStackTrace();
        } catch (IOException e) {
            networkErrorToUi(e);
        }
    }

    /**
     * Displays timetable, no matter whether it has already been downloaded or not.
     * @param table The table to be displayed
     */
    private void displayTimetable(final Table table) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    if (table.isHtml()) {

                        // Possibly init WebView early
                        final SharedPreferences sharedPreferences = u.getSharedPreferences();
                        if (sharedPreferences.getBoolean("renderWebViewEarly", false)) {
                            // Do init async to this thread: use new thread (async to this thread) to then run on ui thread (synchronous to new thread)
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.d("DRAW", "(possibly) initializing WebView while getting file");
                                            initWebView();
                                            mWebView.setVisibility(View.GONE);

                                            // We don't know whether it should be rendered early next time again
                                            sharedPreferences
                                                    .edit()
                                                    .putBoolean("renderWebViewEarly", false)
                                                    .apply();
                                        }
                                    });
                                }
                            }).start();
                        }

                        final String html = mFileManager.getHtmlTable(table, mDownloadManager);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                displayHtml(html);
                            }
                        });
                    } else {
                        final Bitmap image = mFileManager.getImageTable(table, mDownloadManager);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                displayImage(image);
                            }
                        });
                    }

                } catch (final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            networkErrorToUi(e);
                        }
                    });
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * Displays file available offline already
     *
     * @param file   File to be displayed
     * @param isHtml Whether the file is html
     */
    private void displayFile(File file, boolean isHtml) {
        if (isHtml) {
            String html = mFileManager.readHtmlFile(file);
            displayHtml(html);
        } else {
            Bitmap bitmap = mFileManager.readBitmapFile(file);
            displayImage(bitmap);
        }
    }

    private void displayHtml(final String response) {
        // In case an image had been shown previously, hide it
        ImageView image = findViewById(R.id.tableimage);
        image.setVisibility(View.GONE);

        if (mParse) {
            // Parse table

            // Create runnable
            final ReaderRunnable readerRunnable = new ReaderRunnable(MainActivity.this, response,
                    credentialsId, mReaderThreads
            );
            readerRunnable.addHandlers(
                    new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(Message msg) {
                            // Display parsed entries
                            displayEntries(readerRunnable.getResult());

                            if (u.getSharedPreferences().getBoolean(Utility.SUPER_SECRET_SETTING_SCHOOL_NAME_AS_WINDOW_TITLE, getResources().getBoolean(R.bool.school_name_as_window_title_default))) {
                                setTitle(readerRunnable.getSchoolName());
                            }
                            return false;
                        }
                    }),
                    new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(Message msg) {
                            // Display error message
                            displayErrorEntry();
                            return false;
                        }
                    })
            );

            // Start and add thread
            Thread thread = new Thread(readerRunnable);
            mReaderThreads.add(thread);
            thread.start();


        } else {
            ((TextView) findViewById(R.id.date)).setText("");

            // Render HTML code in WebView

            initWebView();
            mWebView.setVisibility(View.VISIBLE);

            // Save that the WebView should be rendered early next time
            u.getSharedPreferences()
                    .edit()
                    .putBoolean("renderWebViewEarly", true)
                    .apply();

            try {
                mWebView.loadData(response, "text/html", null);
            } catch (NullPointerException e) {
                e.printStackTrace();
                mWebView.setVisibility(View.GONE);
                mTextView.setText(getString(R.string.error_displaying));
                mTextView.setVisibility(View.VISIBLE);
            }
        }

        potentiallyDisplayTimetabledate();
    }

    private void initWebView() {
        if (mWebView == null) {
            long webViewInitStart = System.currentTimeMillis();
            mWebView = new WebView(this);
            mWebView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
            );
            ((ViewGroup) findViewById(R.id.content)).addView(mWebView);

            mWebView.getSettings().setJavaScriptEnabled(false);

            Log.d("DRAW", "initialized WebView within " + (System.currentTimeMillis() - webViewInitStart)
                    + " milliseconds");
        }
    }

    private void displayErrorEntry() {
        ArrayList<Entry> error = new ArrayList<>();
        error.add(new Entry(null, null, null, getString(R.string.error_parsing_partial), null, null));
        displayEntries(error);
    }

    private void displayEntries(final ArrayList<Entry> entries) {


        ListView listView = findViewById(R.id.table);

        if (mAdapter == null || !mMerge) {
            mAdapter = new Adapter(MainActivity.this, entries);
            ((TextView) findViewById(R.id.date)).setText("");

            listView.setAdapter(mAdapter);
        } else {
            mAdapter.addAll(entries);
        }

        listView.setVisibility(View.VISIBLE);


        if (mAdapter.size() > 0) {
            mTextView.setVisibility(View.GONE);

            final TextView dateView = findViewById(R.id.date);
            dateView.setVisibility(View.VISIBLE);

            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    try {
                        dateView.setText(u.formatDate(mAdapter.get(firstVisibleItem).getDate()));
                    } catch (IndexOutOfBoundsException | NullPointerException e) {
                        // does not matter because this happens when list is empty
                    }

                }
            });

            // Enable long pressing to share unless super secret setting is enabled
            if (u.getSharedPreferences().getBoolean(Utility.SUPER_SECRET_SETTING_HOLD_TO_SHARE, true)) {
                listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent shareIntent = new Intent(Intent.ACTION_SEND);
                        shareIntent.putExtra(Intent.EXTRA_TEXT, mAdapter.get(position).getShareText(u));
                        shareIntent.setType("text/plain");
                        startActivity(Intent.createChooser(shareIntent, getString(R.string.share_title)));

                        return true;
                    }
                });
            }

        } else {
            mTextView.setText(R.string.empty);
            mTextView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }
    }

    /**
     * Display multiple html tables at once (concatenate them)
     *
     * @param tables Tables to be potentially downloaded and displayed
     */
    private void displayMultipleHtmlTimetables(final ArrayList<Table> tables) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Table table = tables.get(0);

                tables.remove(table);
                try {
                    final String html = mFileManager.getHtmlTable(table, mDownloadManager);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            displayHtml(html);

                            // Display remaining tables
                            // This has to be done after the previous entries have been parsed to not mix up the order
                            if (tables.size() > 0) {
                                // To understand recursion, you first have to understand recursion
                                displayMultipleHtmlTimetables(tables);
                            }
                        }
                    });
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            displayErrorEntry(); // Missing just a part!

                        }
                    });
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void displayImage(Bitmap bitmap) {
        // Hide text
        mTextView.setVisibility(View.GONE);

        // Hide list and webView in case they had previously been displayed
        ListView listView = findViewById(R.id.table);
        listView.setVisibility(View.GONE);

        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
        }

        // Zoom out
        TouchImageView image = findViewById(R.id.tableimage);
        image.resetZoom();

        BitmapDrawable drawable = new BitmapDrawable(bitmap);

        // Invert colors
        if (u.getSharedPreferences().getBoolean("invertImages", false)) {
            // Thanks, https://stackoverflow.com/a/17871384
            final float[] NEGATIVE = {
                    -1.0f, 0, 0, 0, 255, // red
                    0, -1.0f, 0, 0, 255, // green
                    0, 0, -1.0f, 0, 255, // blue
                    0, 0, 0, 1.0f, 0  // alpha
            };
            drawable.setColorFilter(new ColorMatrixColorFilter(NEGATIVE));
        }


        // Show image
        image.setImageDrawable(drawable);
        image.setVisibility(View.VISIBLE);


        potentiallyDisplayTimetabledate();

    }

    private void offlineMode() {

        // Change title to notify user offline mode is enabled
        getSupportActionBar().setTitle(R.string.app_name_offline);

        // Check checkbox
        if (mMenu != null) {
            mMenu.findItem(R.id.action_view_history).setChecked(true);
        }

        // Don't merge
        mMerge = false;

        // Find every file
        final File[] files = mFileManager.listFiles();

        if (files.length == 0) {
            // We're done
            return;
        }

        // Sort files descending by last modified
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.lastModified() < o2.lastModified()) {
                    return 1;
                } else if (o1.lastModified() == o2.lastModified()) {
                    return 0;
                } else if (o1.lastModified() > o2.lastModified()) {
                    return -1;
                }
                // We should never get here but whatever
                return 0;
            }
        });

        // Read every file to a Table
        mTables = new Table[files.length];

        for (int i = 0; i < files.length; i++) {
            File file = files[i];

            String url = file.getName().replaceAll("\\d+-", "");

            Date date;
            // Who knows what files might be in our file system
            try {
                String time = file.getName().split("-")[0];
                date = new Date(Long.parseLong(time));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                date = new Date();
            }

            boolean isHtml;
            try {
                String[] fileNameParts = file.getName().split("\\.");
                String suffix = fileNameParts[fileNameParts.length - 1];

                isHtml = suffix.contains("htm");
            } catch (ArrayIndexOutOfBoundsException e) {
                // In this case, there was no dot in the filename

                isHtml = false;
            }

            mTables[i] = new Table(url, date, isHtml, Humanize.naturalTime(date));
        }

        // Don't do it. It's dumb
        //mTimetabledate = mTables[0].getPublishedDate();

        // Display the first table
        HorizontalPicker pagePicker = findViewById(R.id.page);
        pagePicker.setSelectedItem(0);
        mCurrentTable = mTables[0];
        displayFile(files[0], mTables[0].isHtml());

        // Let user view other files
        if (mTables.length > 1) {
            pagePicker.setVisibility(View.VISIBLE);

            // Initialize CharSequence[] for setting them as values
            CharSequence[] values = new CharSequence[mTables.length];
            for (int i = 0; i < mTables.length; i++) {
                values[i] = Humanize.naturalTime(mTables[i].getPublishedDate());
            }

            pagePicker.setValues(values);
            pagePicker.setOnItemSelectedListener(new HorizontalPicker.OnItemSelected() {
                @Override
                public void onItemSelected(int index) {
                    displayFile(files[index], mTables[index].isHtml());
                }
            });

            pagePicker.setOnItemClickedListener(new HorizontalPicker.OnItemClicked() {
                @Override
                public void onItemClicked(int index) {
                    displayTimetabledate(R.string.timetable_published, mTables[index].getPublishedDate());
                }
            });
        }
    }

    private void potentiallyDisplayTimetabledate() {
        // Only do this once
        if (!mTimetabledateDisplayed && mTimetabledate != null) {
            displayTimetabledate(R.string.timetable_last_changed, mTimetabledate);
            mTimetabledateDisplayed = true;
        }
    }

    private void displayTimetabledate(@StringRes int message, Date mTimetabledate) {
        String ago = Humanize.naturalTime(mTimetabledate, TimeMillis.HOUR);
        if (ago.length() <= 0) {
            ago = Humanize.naturalTime(mTimetabledate, TimeMillis.SECOND);
        }
        Log.d("TIMETABLEDATE", ago);
        Snackbar
                .make(findViewById(R.id.contentCoordinator),
                        getString(message, ago),
                        Snackbar.LENGTH_LONG)
                .show();
    }

    public static void setOverflowButtonColor(final Activity activity, final int color) {
        // from https://stackoverflow.com/a/36278375 by https://stackoverflow.com/users/5064289/barun-kumar
        final String overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description);
        final ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
        final ViewTreeObserver viewTreeObserver = decorView.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                final ArrayList<View> outViews = new ArrayList<View>();
                decorView.findViewsWithText(outViews, overflowDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
                if (outViews.isEmpty()) {
                    return;
                }
                AppCompatImageView overflow = (AppCompatImageView) outViews.get(0);
                overflow.setColorFilter(color);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        if (getResources().getBoolean(R.bool.reauthenticate_button)) {
            menu.add(Menu.NONE, 3, Menu.NONE, R.string.action_reauth);
        }

        // Pass it around!
        mMenu = menu;

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_reload:
                recreate();

                break;
            case R.id.action_view_history:
                if (item.isChecked()) {
                    recreate();
                } else {
                    item.setChecked(true);
                    offlineMode();
                }
                break;
            case R.id.action_settings:
                Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);

                // Pass along whether table is html
                if (mCurrentTable != null) {
                    settingsIntent.putExtra(SettingsActivity.EXTRA_IS_HTML, mCurrentTable.isHtml());
                }

                startActivityForResult(settingsIntent,
                        SettingsActivity.class.getName().length() // I needed a constant number, so I chose something simple & easy to remember
                );
                break;
            case 3:
                startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), REQUEST_LOGIN);
                break;
            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
        return true;
    }

    private void showAuthPrompt() {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle(R.string.credentials_popup_title)
                .setMessage(R.string.credentials_popup_message)
                .setNegativeButton(R.string.dismiss, null)
                .setPositiveButton(R.string.login_login, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), REQUEST_LOGIN);
                    }
                })
                .show();
    }

    @Override
    public void recreate() {
        super.recreate();

        // Reset pagePicker position
        ((HorizontalPicker) findViewById(R.id.page)).setSelectedItem(0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //int settingsActivityRequestCode = SettingsActivity.class.getName().length(); // A way to get a cool number
        // Whatever request this is happened, we want to reload if it was successful
        if (resultCode == RESULT_OK) {
            recreate(); // Because we can't really refresh very well
        } else if (resultCode == RESULT_CANCELED && requestCode == REQUEST_LOGIN) {
            // Login was cancelled, quit if not debug
            if (getResources().getBoolean(R.bool.authenticate_quit_on_cancel))
            finish();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
