package org.keyscience.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.Toast;

import org.keyscience.Database.DatabaseHelper;
import org.keyscience.Database.EcoQuestDBContract;
import org.keyscience.R;
import org.keyscience.SingletonPattern.SingletonFragmentList;
import org.keyscience.SingletonPattern.User;
import org.keyscience.fragments.AboutUsFragment;
import org.keyscience.fragments.ContactUsFragment;
import org.keyscience.fragments.CspLearnFragment;
import org.keyscience.fragments.CspRecordFragment;
import org.keyscience.fragments.DummyFragment;
import org.keyscience.fragments.DynamicContentFragment;
import org.keyscience.fragments.FieldActivitiesFragment;
import org.keyscience.fragments.HomeFragment;
import org.keyscience.fragments.KeyChallengeFragment;
import org.keyscience.fragments.LectureSeriesFragment;
import org.keyscience.fragments.LoginFragment;
import org.keyscience.fragments.MiniChallengeFragment;
import org.keyscience.fragments.NewslettersFragment;
import org.keyscience.fragments.OurBiomesFragment;
import org.keyscience.fragments.OurPartnersFragment;
import org.keyscience.fragments.PreviousWinnersFragment;
import org.keyscience.fragments.ProfileFragment;
import org.keyscience.fragments.ReefRestoChildFragment;
import org.keyscience.fragments.ReefRestorationFragment;
import org.keyscience.fragments.SeaLevelRiseFragment;
import org.keyscience.fragments.SectionsStatePagerAdapter;
import org.keyscience.fragments.WaterQualityFragment;
import org.keyscience.fragments.WaterWatchFragment;

import java.io.File;
import java.util.HashSet;

public class HomeActivity extends AppCompatActivity {

    private DatabaseHelper dbHelper;
    private Toolbar toolbar;
    public static ViewPager viewPager;
    private int lastFragment;
    private DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        viewPager = (NonSwipeViewPager) findViewById(R.id.fragmentContainer);
        loadUser();
        setUpViewPager();
        // this methods most be called after setUpViewPager()
        setUpToolBar();
        setUpNavDrawer();
    }

    private void loadUser() {
        // check if user session is active
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARE_PRE_FILE, Context.MODE_PRIVATE);
        // if user already logged in using remember me
        if (sharedPreferences.getLong(Constants.PERSISTENT_SESSION, -1) >= 0) {

            dbHelper = new DatabaseHelper(this);

            SQLiteDatabase db = dbHelper.getReadableDatabase();

            // Define a projection that specifies which columns from the database
            // you will actually use after this query.
            String[] projection = {
                    EcoQuestDBContract.UserTable.NAME,
                    EcoQuestDBContract.UserTable._ID,
                    EcoQuestDBContract.UserTable.EMAIL,
                    EcoQuestDBContract.UserTable.BIO,
                    EcoQuestDBContract.UserTable.RANK,
                    EcoQuestDBContract.UserTable.POINTS,
                    EcoQuestDBContract.UserTable.TOTAL_COMPLETED_QUESTS,
            };

            String selection = EcoQuestDBContract.UserTable._ID + " = ?";
            String[] selectionArgs = {"" + sharedPreferences.getLong(Constants.PERSISTENT_SESSION, -1)};

            // How you want the results sorted in the resulting Cursor
            String sortOrder =
                    EcoQuestDBContract.UserTable._ID + " DESC";

            Cursor cursor = db.query(
                    EcoQuestDBContract.UserTable.TABLE_NAME,   // The table to query
                    projection,             // The array of columns to return (pass null to get all)
                    selection,              // The columns for the WHERE clause
                    selectionArgs,          // The values for the WHERE clause
                    null,                   // don't group the rows
                    null,                   // don't filter by row groups
                    sortOrder               // The sort order
            );

            if (cursor.moveToNext()) {
                // set user instance for the session
                String userID = cursor.getString(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable._ID));
                String email = cursor.getString(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable.EMAIL));
                String userName = cursor.getString(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable.NAME));
                String userBio = cursor.getString(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable.BIO));
                String userRank = cursor.getString(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable.RANK));
                int userTotalPoints = cursor.getInt(cursor.getColumnIndexOrThrow(EcoQuestDBContract.UserTable.POINTS));

                User.getInstance(Long.parseLong(userID), userName
                        , email,
                        userBio, userTotalPoints,
                        userRank,
                        getCompletedQuests(dbHelper, userID));
            }
            cursor.close();
        }
    }

    private HashSet<Integer> getCompletedQuests(DatabaseHelper dbHelper, String userID) {

        HashSet<Integer> questsID = new HashSet<>();

        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // Define a projection that specifies which columns from the database
        // you will actually use after this query.
        String[] projection = {
                EcoQuestDBContract.CompletedQuest.QUEST_ID
        };

        String selection = EcoQuestDBContract.CompletedQuest.USER_ID + " = ?";
        String[] selectionArgs = {userID};

        // How you want the results sorted in the resulting Cursor
        String sortOrder =
                EcoQuestDBContract.CompletedQuest.QUEST_ID + " DESC";

        Cursor cursor = db.query(
                EcoQuestDBContract.CompletedQuest.TABLE_NAME,   // The table to query
                projection,             // The array of columns to return (pass null to get all)
                selection,              // The columns for the WHERE clause
                selectionArgs,          // The values for the WHERE clause
                null,                   // don't group the rows
                null,                   // don't filter by row groups
                sortOrder               // The sort order
        );

        // add all completed quests IDs to the set
        while (cursor.moveToNext()) {
            questsID.add(cursor.getInt(cursor.getColumnIndexOrThrow(EcoQuestDBContract.CompletedQuest.QUEST_ID)));
        }
        cursor.close();

        return questsID;
    }


    @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() == SingletonFragmentList.getInstance().getFragmentPosition(Constants.LOGIN) ||
                viewPager.getCurrentItem() == SingletonFragmentList.getInstance().getFragmentPosition(Constants.PROFILE))
            return;

        // set fragment to las visited
        setViewPager(lastFragment);

        // Close drawer when back button is pressed
        drawerLayout = HomeActivity.this.findViewById(R.id.drawer_layout);
        drawerLayout.closeDrawers();
    }

    private void setUpToolBar() {
        // setup toolbar as action bar
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(Constants.TITLE);
        toolbar.setSubtitle(Constants.CITIZEN_SCIENTIST_PROJECT);
    }

    private void setUpNavDrawer() {
        NavDrawerFragment navDrawerFragment = (NavDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.nav_drwr_fragment);
        DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
        navDrawerFragment.setUpDrawer(R.id.nav_drwr_fragment, drawerLayout, toolbar);
    }

    private void setUpViewPager() {
        SectionsStatePagerAdapter adapter = SectionsStatePagerAdapter.getInstanceSectionsStatePagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new HomeFragment(), Constants.HOME);

        adapter.addFragment(new KeyChallengeFragment(), Constants.KEY_CHALLENGE);
        adapter.addFragment(new ReefRestorationFragment(), Constants.REEF_RESTORATION);
        adapter.addFragment(new WaterWatchFragment(), Constants.WATER_WATCH);
        adapter.addFragment(new SeaLevelRiseFragment(), Constants.SEA_LEVEL_RISE);
        adapter.addFragment(new LectureSeriesFragment(), Constants.LECTURE_SERIES);
        adapter.addFragment(new FieldActivitiesFragment(), Constants.FIELD_ACTIVITIES);
        adapter.addFragment(new OurPartnersFragment(), Constants.OUR_PARTNERS);
        adapter.addFragment(new ContactUsFragment(), Constants.CONTACT_US);

        // setup Events
        Bundle bundle = new Bundle();
        bundle.putString("json", Constants.jsonUrlEvents);
        bundle.putString("php", Constants.phpUrlEvents);
        bundle.putString("readMoreLink", Constants.readMoreEvents);
        bundle.putInt("listType", 0); // 0 to build list of type Events
        DynamicContentFragment dynamicContentFragment = new DynamicContentFragment();
        dynamicContentFragment.setArguments(bundle);
        adapter.addFragment(dynamicContentFragment, Constants.EVENTS);

        // setup News
        Bundle bundleNews = new Bundle();
        bundleNews.putString("json", Constants.jsonUrlNews);
        bundleNews.putString("readMoreLink", Constants.readMoreNews);
        bundleNews.putString("php", Constants.phpUrlNews);
        bundleNews.putInt("listType", 1); // 1 to build list of type News
        DynamicContentFragment newsFragment = new DynamicContentFragment();
        newsFragment.setArguments(bundleNews);
        adapter.addFragment(newsFragment, Constants.NEWS);

        adapter.addFragment(new AboutUsFragment(), Constants.ABOUT_US);
        adapter.addFragment(new NewslettersFragment(), Constants.NEWSLETTERS);
        adapter.addFragment(new OurBiomesFragment(), Constants.OUR_BIOMES);

        adapter.addFragment(new CspLearnFragment(), Constants.CSP_LEARN);
        adapter.addFragment(new DummyFragment(), Constants.CSP_EXPLORE);
        adapter.addFragment(new CspRecordFragment(), Constants.CSP_RECORD);
        adapter.addFragment(new HomeFragment(), Constants.CSP_REVIEW);

        adapter.addFragment(new WaterQualityFragment(), Constants.WATER_QUALITY);
        adapter.addFragment(new MiniChallengeFragment(), Constants.MINI_CHALLENGE);
        adapter.addFragment(new PreviousWinnersFragment(), Constants.KEY_CHALLENGE_WINNERS);
        adapter.addFragment(new ReefRestoChildFragment(), Constants.REEF_RESTORATION_CHILD);

        adapter.addFragment(new LoginFragment(), Constants.LOGIN);
        adapter.addFragment(new ProfileFragment(), Constants.PROFILE);

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(1);
        lastFragment = viewPager.getCurrentItem();
    }

    public void setViewPager(int fragmentNumber) {
        lastFragment = viewPager.getCurrentItem(); // save fragment so we can return to it
        viewPager.setCurrentItem(fragmentNumber);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CHECK_SETTINGS) {
            if (resultCode == HomeActivity.RESULT_OK) {
                // Location Services Activated
                Intent intent = new Intent();
                intent.setAction(Constants.LOCATION_ACTION);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            } else {
                Toast.makeText(this, "Location Services Needed to Play EcoQuest", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // Check if location permissions are granted and if so enable the
        // location data layer.
        switch (requestCode) {
            case Constants.REQUEST_LOCATION_PERMISSION:
                if (grantResults.length > 0
                        && grantResults[0]
                        == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Constants.LOCATION_ACTION);
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
                    break;
                } else {
                    Toast.makeText(this, "Location Access Needed to Play EcoQuest", Toast.LENGTH_SHORT).show();
                }
        }
    }

    @Override
    protected void onDestroy() {
        if (dbHelper != null) {
            dbHelper.close();
        }
        super.onDestroy();
    }
}
