package com.hyperling.apps.wheretheriverfrowns;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;

    private String sharedPreferencesKey, topArticleKey, externalBrowserKey, checkForNewArticlesKey, debugKey,
            networkConnected, networkRoaming, networkDisconnected,
            TAG,
            action, url;

    private ActionBar actionBar;

    private ProgressBar progressBar;

    private LinearLayout layout;
    private Button btnExample;

    private boolean homePage, externalBrowser;

    private boolean DEBUG;

    private WebPage webPage;

    private int debugCount, debugMax = 13;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*** Initialize Strings ***/
        // Keys
        sharedPreferencesKey = getResources().getString(R.string.sharedPreferencesKey);
        topArticleKey = getResources().getString(R.string.topArticleKey);
        externalBrowserKey = getResources().getString(R.string.externalBrowserKey);
        checkForNewArticlesKey = getResources().getString(R.string.checkForNewArticlesKey);
        debugKey = getString(R.string.debugKey);

        // Strings
        networkConnected = getResources().getString(R.string.networkConnected);
        networkRoaming = getResources().getString(R.string.networkRoaming);
        networkDisconnected = getResources().getString(R.string.networkDisconnected);
        TAG = getResources().getString(R.string.TAG);

        /*** Get Preferences ***/
        sharedPreferences = getSharedPreferences(sharedPreferencesKey, MODE_PRIVATE);
        externalBrowser = sharedPreferences.getBoolean(externalBrowserKey, true);
        DEBUG = sharedPreferences.getBoolean(debugKey, false);

        /*** Initialize UI Objects ***/
        actionBar = MainActivity.this.getSupportActionBar();
        actionBar.setTitle(getString(R.string.app_title));
        actionBar.setHomeButtonEnabled(true);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        layout = (LinearLayout) findViewById(R.id.layout);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                debugCount++;
                if (debugCount >= debugMax) {
                    Intent debugIntent = new Intent(MainActivity.this, DebugActivity.class);
                    startActivity(debugIntent);
                }
                if (DEBUG) {
                    Log.d(TAG, "MainActivity:  debugCount=" + debugCount);
                }
            }
        });

        btnExample = (Button) findViewById(R.id.btnExample);

        // Data checks
        action = MainActivity.this.getIntent().getAction();
        if (action.isEmpty() || !action.contains("http")) {
            url = getResources().getString(R.string.allStories);
            homePage = true;
        } else {
            url = action;
            homePage = false;
        }
        if (DEBUG) Log.d(TAG, "MainActivity:  action=" + action + " url=" + url);

        // Allow webpage download
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        // Start the fun
        this.refreshWebPage();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private String isNetworkAvailable() {
        NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        try {
            if (info.isConnected()) {
                return networkConnected;
            } else if (info.isRoaming()) {
                return networkRoaming;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return networkDisconnected;
    }

    private void refreshWebPage() {
        String status = isNetworkAvailable();

        if (status.equals(networkConnected)) {
            Runnable getWebsiteData = new Runnable() {
                @Override
                public void run() {
                    webPage = new WebPage(getBaseContext(), url);
                    loadArticles.sendEmptyMessage(0);
                }
            };

            Thread t = new Thread(getWebsiteData);
            progressBar.setIndeterminate(true);
            progressBar.setVisibility(View.VISIBLE);
            t.start();
        } else if (status.equals(networkRoaming)) {
            Toast.makeText(this, "Currently Roaming -- Not Updating", Toast.LENGTH_LONG).show();
        } else if (status.equals(networkDisconnected)) {
            Toast.makeText(this, "Network Connection Not Found", Toast.LENGTH_LONG).show();
        }
    }

    private Handler loadArticles = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            layout.removeAllViews();

            progressBar.setMax(webPage.getTitles().size());

            int index;

            for (String title : webPage.getTitles()) {
                index = webPage.getTitles().indexOf(title);

                progressBar.setProgress(index);
                progressBar.invalidate();

                String date = webPage.getDates().get(index);
                if (DEBUG) Log.d(TAG, "MainActivity:  date=" + date + " title=" + title);
                String text = date + '\n' + title;

                // If we are on all-stories and on the first article
                if (homePage && webPage.getTitles().indexOf(title) == 0) {
                    // Only update the Top Article if necessary
                    String oldTitle = sharedPreferences.getString(topArticleKey, "");
                    if (!oldTitle.equals(title)) {
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(topArticleKey, title);
                        editor.apply();
                        if (DEBUG) Log.d(TAG, "MainActivity:  Top Article updated.");
                    }

                    if (DEBUG) {
                        Log.d(TAG, "MainActivity:  title=" + title);
                        Log.d(TAG, "MainActivity:  oldTitle=" + oldTitle);
                        Log.d(TAG, "MainActivity:  sharedPreferences.TopArticle=" + sharedPreferences.getString(topArticleKey, ""));
                    }
                }

                // Display all articles
                if (!action.equals(url)) {
                    TextView spacer = new TextView(btnExample.getContext());
                    Button btn = new Button(btnExample.getContext());
                    btn.setText(text);
                    if (sharedPreferences.getBoolean(title, false)) {
                        btn.setBackgroundColor(getResources().getColor(R.color.articleRead));
                    } else {
                        btn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                    }
                    btn.setTextColor(Color.WHITE);
                    btn.setVisibility(View.VISIBLE);
                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Button b = (Button) v;

                            String text = b.getText().toString();
                            int newline = text.indexOf('\n');

                            String articleTitle = text.substring(newline + 1);
                            String articleLink = webPage.getLinks().get(webPage.getTitles().indexOf(articleTitle));

                            if (externalBrowser) {
                                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(articleLink));
                                startActivity(browserIntent);
                            } else {
                                Intent openArticle = new Intent(MainActivity.this, MainActivity.class);
                                openArticle.setAction(articleLink);
                                MainActivity.this.startActivity(openArticle);
                            }

                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putBoolean(articleTitle, true);
                            editor.apply();

                            b.setBackgroundColor(getResources().getColor(R.color.articleRead));
                        }
                    });
                    layout.addView(spacer);
                    layout.addView(btn);
                }
                // Internal browser
                else {
                    TextView btn = new TextView(btnExample.getContext());
                    btn.setText(date + '\n' + title);
                    btn.setTextColor(getResources().getColor(R.color.colorPrimary));
                    btn.setTextSize(20);
                    btn.setVisibility(View.VISIBLE);
                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            TextView b = (TextView) v;

                            String text = b.getText().toString();
                            int newline = text.indexOf('\n');

                            String articleTitle = text.substring(newline + 1);
                            String articleLink = webPage.getLinks().get(webPage.getTitles().indexOf(articleTitle));

                            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(articleLink));
                            startActivity(browserIntent);
                        }
                    });

                    layout.addView(btn);
                }
            }

            if (webPage.getTitles().size() == 1) {
                layout.addView(webPage.getContent());
            }

            progressBar.setVisibility(View.GONE);

            // Reschedule the service
            Intent restartService = new Intent(MainActivity.this, MyService.class);
            startService(restartService);

            super.handleMessage(msg);
        }
    };

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

        MenuItem refresh = menu.findItem(R.id.refresh);
        refresh.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                refreshWebPage();
                return true;
            }
        });

        MenuItem checkForNewArticles = menu.findItem(R.id.checkForNewArticles);
        checkForNewArticles.setChecked(sharedPreferences.getBoolean(checkForNewArticlesKey, true));

        MenuItem externalBrowser = menu.findItem(R.id.externalBrowser);
        externalBrowser.setChecked(sharedPreferences.getBoolean(externalBrowserKey, true));

        return super.onCreateOptionsMenu(menu);
    }
/*
    @Override
    public void onOptionsMenuClosed(Menu menu) {
        super.onOptionsMenuClosed(menu);
    }
*/
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        String menuItemKey;

        switch (id) {
            case R.id.externalBrowser:
                menuItemKey = externalBrowserKey;
                break;
            case R.id.checkForNewArticles:
                menuItemKey = checkForNewArticlesKey;
                break;
            default:
                return super.onOptionsItemSelected(item);
        }

        boolean newValue = !sharedPreferences.getBoolean(menuItemKey, true);

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(menuItemKey, newValue);
        editor.apply();

        if (id == R.id.externalBrowser) {
            finish();
            startActivity(this.getIntent());
        }

        item.setChecked(newValue);

        Toast.makeText(this, "Settings saved.", Toast.LENGTH_LONG).show();
        return true;
    }

    @Override
    protected void onResume() {
        debugCount = 0;

        super.onResume();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

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

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
