package fr.android.pointspermis;

import android.app.Activity;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.TextView;

import java.io.File;
import java.util.List;

import fr.android.pointspermis.captcha.Captcha;
import fr.android.pointspermis.settings.ConfigActivity;
import fr.android.pointspermis.settings.SettingsActivity;
import fr.android.pointspermis.tools.AssetsTools;
import fr.android.pointspermis.web.WebTask;


public class MainActivity extends Activity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    public final static String SOLDE_KEY = "solde";
    public final static String USERNAME_KEY = "username";
    public final static String BIRTHDAY_KEY = "birthday";

    private final Context context = this;

    private ActionBar actionBar;

    private WebTask webform;

    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;

    private String solde;
    private String username;
    private String birthday;


    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private FragmentManager fragmentManager;
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private PlaceholderFragment mPlaceholderFrament;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Routines
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Strict thread mode
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        // Copy tesseract data to app-specific internal storage (language stuff)
        copyTesseractData();

        // Get actionBar
        actionBar = getActionBar();

        // Get fragment manager
        fragmentManager = getFragmentManager();

        // Set up the drawer.
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                fragmentManager.findFragmentById(R.id.navigation_drawer);
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout)
        );
        // Load prefs
        prefs = getSharedPreferences("fr.android.pointspermis", MODE_PRIVATE);
        editor = prefs.edit();

        // Try to get saved values
        solde = prefs.getString(SOLDE_KEY, "            ");
        username = prefs.getString(USERNAME_KEY, "");
        birthday = prefs.getString(BIRTHDAY_KEY, "");

        // Set the main fragment with args
        mPlaceholderFrament = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putString(SOLDE_KEY, solde);
        args.putString(USERNAME_KEY, username);
        args.putString(BIRTHDAY_KEY, birthday);
        mPlaceholderFrament.setArguments(args);
        fragmentManager.beginTransaction().replace(R.id.container, mPlaceholderFrament).commit();
    }

    public void copyTesseractData() {

        // Copy tesseract data to app-specific internal storage (language stuff)
        File filesDir = getFilesDir();
        if (!getFilesDir().canRead()) { getFilesDir().setReadable(true); }
        if (!getFilesDir().canWrite()) { getFilesDir().setWritable(true); }
        if (!getFilesDir().exists()) { getFilesDir().mkdir(); }
        boolean dirExists = false;
        for (String fod : getFilesDir().list()) { if (fod.contains(Captcha.TESSBASE_DIR)) { dirExists = true; break; } }
        if (!dirExists && getFilesDir().getFreeSpace() < (31 * 1024 * 1024)) {
            new AlertDialog.Builder(this)
                    .setTitle("Erreur fatale !")
                    .setMessage("Impossible de copier les données nécessaires au fonctionnement de l'application, "+
                            "veuillez vous assurer de disposer d'au moins 30Mo d'espace de stockage interne disponible.")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            MainActivity.this.finish();
                        }
                    })
                    .show();
        }
        AssetsTools.copyFileOrDir(Captcha.TESSBASE_DIR, filesDir.getPath() + '/', getAssets());
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        /* update the main content by replacing fragments
        mPlaceholderFrament = PlaceholderFragment.newInstance(position + 1);
        fragmentManager.beginTransaction().replace(R.id.container, mPlaceholderFrament).commit();*/

        // Manage actions on drawer's clicks
        if (position == 0) {
            Intent i = new Intent(this, ConfigActivity.class);
            startActivity(i);
        }
        if (position == 1) {
            Intent i = new Intent(this, SettingsActivity.class);
            startActivity(i);
        }
        if (position == 2) {
            quit();
        }
    }

    public void restoreActionBar() {
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(R.string.app_name);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @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.action_config) {
            Intent i = new Intent(this, ConfigActivity.class);
            startActivity(i);
            return true;
        }

        if (id == R.id.action_settings) {
            Intent i = new Intent(this, SettingsActivity.class);
            startActivity(i);
            return true;
        }

        if (item.getItemId() == R.id.action_refresh) {

            // Initialize and execute the WebForm async task
            webform = new WebTask(context, MainActivity.this);
            webform.execute(prefs.getString(ConfigActivity.DOSSIER1_KEY, ""),
                    prefs.getString(ConfigActivity.DOSSIER2_KEY, ""),
                    prefs.getString(ConfigActivity.DOSSIER3_KEY, ""),
                    prefs.getString(ConfigActivity.CODE_KEY, "")
            );
            return true;
        }

        if (item.getItemId() == R.id.action_quit) {
            quit();
        }

        return super.onOptionsItemSelected(item);
    }

    public void setInfos(List<String> infos) {

        // Store infos
        solde = infos.get(0);
        username = infos.get(1);
        birthday = infos.get(2);

        saveUserData();

        // Set infos to the fragment
        mPlaceholderFrament.setInfos(infos);
    }

    private void saveUserData() {

        editor.putString(SOLDE_KEY, solde);
        editor.putString(USERNAME_KEY, username);
        editor.putString(BIRTHDAY_KEY, birthday);
        editor.commit();
    }

    public void quit() {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.question_quit))
                .setCancelable(false)
                .setPositiveButton(getString(R.string.action_yes), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        // Save user data
                        saveUserData();

                        // Terminate activity
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton(getString(R.string.action_no), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onBackPressed() {
        quit();
    }

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

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}
