package com.peacock.fantafone;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.IntentCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.peacock.fantafone.pages.Home0Calendar;
import com.peacock.fantafone.pages.Home1Chart;
import com.peacock.fantafone.pages.Tab0Home;
import com.peacock.fantafone.pages.Tab2Drivers;
import com.peacock.fantafone.pages.Tab3Stats;
import com.peacock.fantafone.pages.TabBrowser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.peacock.fantafone.Utils.confirmDrivers;
import static com.peacock.fantafone.Utils.calcAllDrivers;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    public static Context context;
    public static AppCompatActivity a;
    public static RelativeLayout rl_main;
    Toolbar toolbar;
    protected static DatabaseReference root, auth;
    static AlertDialog alertDialog;
    static RelativeLayout[] rl_dm = new RelativeLayout[30];
    static String d1, d2, d3, d4;
    static String key = "";

    //MEMBERS
    public static ArrayList<String> list_of_members = new ArrayList<>();
    public static ArrayList<String> list_of_membersvalues = new ArrayList<>();

    //GRANPRIX
    public static ArrayList<String> list_of_gp = new ArrayList<>();
    public static ArrayList<String> list_of_gpvalues = new ArrayList<>();


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

        Constant.activityState = 1;
        context = this;
        a = this;
        loadPreferences();
        Constant.nickname = Constant.nickname.substring(Constant.nickname.length() - 3, Constant.nickname.length());
        setContent();
    }

    @SuppressWarnings("deprecation")
    private void setContent() {
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        rl_main = (RelativeLayout) findViewById(R.id.rl_main);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.app_name, R.string.app_name);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fl_main, new Tab0Home())
                .commit();
        toolbar.setTitle(R.string.app_name);
        navigationView.setCheckedItem(R.id.n_home);
        navigationView.getHeaderView(0);


        //** FIREBASE DATABASE **//
        root = FirebaseDatabase.getInstance().getReference("room_names").child(Constant.fanta);
        auth = FirebaseDatabase.getInstance().getReference("authData");

        root.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                list_of_membersvalues.clear();
                list_of_members.clear();
                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    list_of_members.add(childDataSnapshot.getKey());
                    list_of_membersvalues.add((String) childDataSnapshot.getValue());
                }

                String ownData = "";
                String ownNICK = "";
                for (int j = 0; j < list_of_members.size(); j++) {
                    if (list_of_members.get(j).split(",").length == 2) {
                        if (list_of_members.get(j).split(",")[1].equals(Constant.nickname)) {
                            ownData = list_of_membersvalues.get(j);
                            key = list_of_members.get(j);
                            invalidateOptionsMenu();
                            ownNICK = list_of_members.get(j).split(",")[1];
                        }
                    }
                }
                if (ownData.equals("") && Constant.drivers.equals("")) selectDrivers();
                else if (!ownData.equals("")) {
                    Utils.setOwnDrivers(ownData);
                    if(!Constant.drivers.equals(ownData)){
                        Map<String, Object> map = new HashMap<>();
                        map.put(key, Constant.drivers);
                        root.updateChildren(map);
                    }
                }

                if (!Constant.nickname.equals(ownNICK) && (ownNICK.length() == 3)) {
                    Constant.nickname = ownNICK;
                    SharedPreferences s = PreferenceManager.getDefaultSharedPreferences(context);
                    SharedPreferences.Editor e = s.edit();
                    e.putString("nickname", Constant.nickname);
                    e.commit();
                }
                if (!Constant.drivers.equals("") && (list_of_gp.size() == list_of_gpvalues.size()) && list_of_gp.size() > 0
                        && (list_of_members.size() == list_of_membersvalues.size()) && list_of_members.size() > 0) {
                    new calcGP().execute();
                }
                if(!Constant.members_contents.equals("")){
                    int numFree = 0;
                    String[] z = Constant.members_contents.split("\\|");
                    for (String splitted: z) if(splitted.equals("a")) numFree++;

                    if(numFree!=10-list_of_members.size()){
                        if (!Constant.drivers.equals("") && (list_of_gp.size() == list_of_gpvalues.size()) && list_of_gp.size() > 0
                                && (list_of_members.size() == list_of_membersvalues.size()) && list_of_members.size() > 0) {
                            Constant.gpGone=0;
                            Constant.members_contents = "a|a|a|a|a|a|a|a|a|a";
                            Constant.d1_points = "";
                            Constant.d2_points = "";
                            Constant.d3_points = "";
                            Constant.d4_points = "";
                            new calcGP().execute();
                        }
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

        root.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {}

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

        auth.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                list_of_gpvalues.clear();
                list_of_gp.clear();
                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    list_of_gp.add(childDataSnapshot.getKey());
                    list_of_gpvalues.add((String) childDataSnapshot.getValue());
                }

                String[] temp = Constant.gpdatas.split(";");
                Constant.gpdatas = "";
                for (int m = 0; m < list_of_gpvalues.size(); m++) {
                    if (!temp[m].equals(list_of_gpvalues.get(m))) temp[m] = list_of_gpvalues.get(m) + ";";
                    Constant.gpdatas += temp[m];
                }

                for (int m = Constant.gpdatas.split(";").length; m < Constant.GP_LEN; m++)  Constant.gpdatas += "a;";
                Utils.savePreference("gpdatas", Constant.gpdatas);

                if (!Constant.drivers.equals("") && (list_of_gp.size() == list_of_gpvalues.size()) && list_of_gp.size() > 0
                        && (list_of_members.size() == list_of_membersvalues.size()) && list_of_members.size() > 0) {
                    new calcGP().execute();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });


    }



    private class calcGP extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            for (int i = Constant.gpGone; i < list_of_gp.size(); i++) {
                Constant.output = list_of_gpvalues.get(i);
                calcAllDrivers();
                if (!Constant.drivers.equals("")) Constant.gpGone++;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            Home0Calendar.setDriversText();
            Home0Calendar.setPointsGP();
            Home0Calendar.setPointsText();
            Home1Chart.setChart();
            SharedPreferences s = PreferenceManager.getDefaultSharedPreferences(MainActivity.context);
            SharedPreferences.Editor e = s.edit();
            e.putString("d1", Constant.d1_points);
            e.putString("d2", Constant.d2_points);
            e.putString("d3", Constant.d3_points);
            e.putString("d4", Constant.d4_points);
            e.putInt("gpgone", Constant.gpGone);
            e.putString("gpdatas", Constant.gpdatas);
            e.commit();
        }
    }


    //** PREFERENCES **//
    private void loadPreferences(){
        SharedPreferences g1 = PreferenceManager.getDefaultSharedPreferences(this);
        Constant.fanta = g1.getString("fanta", Constant.fanta);
        Constant.nickname = g1.getString("nickname", Constant.nickname);
        Constant.gpGone = g1.getInt("gpgone", Constant.gpGone);
        Constant.gpdatas = g1.getString("gpdatas", Constant.gpdatas);
        Constant.drivers = g1.getString("drivers", Constant.drivers);
        Constant.d1_points = g1.getString("d1", Constant.d1_points);
        Constant.d2_points = g1.getString("d2", Constant.d1_points);
        Constant.d3_points = g1.getString("d3", Constant.d1_points);
        Constant.d4_points = g1.getString("d4", Constant.d1_points);
        Constant.members_contents = g1.getString("contents", Constant.members_contents);
    }


    //** SELECT DRIVERS **//
    protected static void setDriversIDs(View v) {
        rl_dm[0] = (RelativeLayout) v.findViewById(R.id.dm_1);
        rl_dm[1] = (RelativeLayout) v.findViewById(R.id.dm_2);
        rl_dm[2] = (RelativeLayout) v.findViewById(R.id.dm_3);
        rl_dm[3] = (RelativeLayout) v.findViewById(R.id.dm_4);
        rl_dm[4] = (RelativeLayout) v.findViewById(R.id.dm_5);
        rl_dm[5] = (RelativeLayout) v.findViewById(R.id.dm_6);
        rl_dm[6] = (RelativeLayout) v.findViewById(R.id.dm_7);
        rl_dm[7] = (RelativeLayout) v.findViewById(R.id.dm_8);
        rl_dm[8] = (RelativeLayout) v.findViewById(R.id.dm_9);
        rl_dm[9] = (RelativeLayout) v.findViewById(R.id.dm_10);
        rl_dm[10] = (RelativeLayout) v.findViewById(R.id.dm_11);
        rl_dm[11] = (RelativeLayout) v.findViewById(R.id.dm_12);
        rl_dm[12] = (RelativeLayout) v.findViewById(R.id.dm_13);
        rl_dm[13] = (RelativeLayout) v.findViewById(R.id.dm_14);
        rl_dm[14] = (RelativeLayout) v.findViewById(R.id.dm_15);
        rl_dm[15] = (RelativeLayout) v.findViewById(R.id.dm_16);
        rl_dm[16] = (RelativeLayout) v.findViewById(R.id.dm_17);
        rl_dm[17] = (RelativeLayout) v.findViewById(R.id.dm_18);
        rl_dm[18] = (RelativeLayout) v.findViewById(R.id.dm_19);
        rl_dm[19] = (RelativeLayout) v.findViewById(R.id.dm_20);
        rl_dm[20] = (RelativeLayout) v.findViewById(R.id.dm_s7);
        rl_dm[21] = (RelativeLayout) v.findViewById(R.id.dm_s8);
        rl_dm[22] = (RelativeLayout) v.findViewById(R.id.dm_s9);
        rl_dm[23] = (RelativeLayout) v.findViewById(R.id.dm_s10);
        rl_dm[24] = (RelativeLayout) v.findViewById(R.id.dm_s11);
        rl_dm[25] = (RelativeLayout) v.findViewById(R.id.dm_s12);
        rl_dm[26] = (RelativeLayout) v.findViewById(R.id.dm_s13);
        rl_dm[27] = (RelativeLayout) v.findViewById(R.id.dm_s14);
        rl_dm[28] = (RelativeLayout) v.findViewById(R.id.dm_s15);
        rl_dm[29] = (RelativeLayout) v.findViewById(R.id.dm_s16);
    }
    protected static class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dm_1:
                    selectDriversUI(0);
                    break;
                case R.id.dm_2:
                    selectDriversUI(1);
                    break;
                case R.id.dm_3:
                    selectDriversUI(2);
                    break;
                case R.id.dm_4:
                    selectDriversUI(3);
                    break;
                case R.id.dm_5:
                    selectDriversUI(4);
                    break;
                case R.id.dm_6:
                    selectDriversUI(5);
                    break;
                case R.id.dm_7:
                    selectDriversUI(6);
                    break;
                case R.id.dm_8:
                    selectDriversUI(7);
                    break;
                case R.id.dm_9:
                    selectDriversUI(8);
                    break;
                case R.id.dm_10:
                    selectDriversUI(9);
                    break;
                case R.id.dm_11:
                    selectDriversUI(10);
                    break;
                case R.id.dm_12:
                    selectDriversUI(11);
                    break;
                case R.id.dm_13:
                    selectDriversUI(12);
                    break;
                case R.id.dm_14:
                    selectDriversUI(13);
                    break;
                case R.id.dm_15:
                    selectDriversUI(14);
                    break;
                case R.id.dm_16:
                    selectDriversUI(15);
                    break;
                case R.id.dm_17:
                    selectDriversUI(16);
                    break;
                case R.id.dm_18:
                    selectDriversUI(17);
                    break;
                case R.id.dm_19:
                    selectDriversUI(18);
                    break;
                case R.id.dm_20:
                    selectDriversUI(19);
                    break;
                case R.id.dm_s7:
                    selectDriversUI(20);
                    break;
                case R.id.dm_s8:
                    selectDriversUI(21);
                    break;
                case R.id.dm_s9:
                    selectDriversUI(22);
                    break;
                case R.id.dm_s10:
                    selectDriversUI(23);
                    break;
                case R.id.dm_s11:
                    selectDriversUI(24);
                    break;
                case R.id.dm_s12:
                    selectDriversUI(25);
                    break;
                case R.id.dm_s13:
                    selectDriversUI(26);
                    break;
                case R.id.dm_s14:
                    selectDriversUI(27);
                    break;
                case R.id.dm_s15:
                    selectDriversUI(28);
                    break;
                case R.id.dm_s16:
                    selectDriversUI(29);
                    break;
            }
        }
    }
    public static void selectDrivers(){
        LayoutInflater inflater = a.getLayoutInflater();
        View dialoglayout = inflater.inflate(R.layout.al_select_drivers, null);
        @SuppressLint("RestrictedApi") final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
        builder.setView(dialoglayout);

        setDriversIDs(dialoglayout);

        for(RelativeLayout cd: rl_dm)
            cd.setOnClickListener(new ClickListener());

        rl_dm[21].setBackgroundResource(R.drawable.ic_select_on);
        d1=Constant.driver_names[0];
        d2=Constant.driver_names[6];
        d3=Constant.driver_names[7];
        d4=Constant.driver_names[16];


        Button ok = (Button) dialoglayout.findViewById(R.id.btn_ok);
        ok.setOnClickListener(view -> confirmDrivers(d1+d2+d3+d4));

        Button canc = (Button) dialoglayout.findViewById(R.id.btn_cance);
        canc.setOnClickListener(view -> alertDialog.cancel());
        alertDialog = builder.create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }
    private static void selectDriversUI(int position) {
        int start=0; int end=0;
        if(position<6) {  d1 = Constant.driver_names[position]; start = 0; end = 6;}
        else if(position>5&&position<16) { d2 = Constant.driver_names[position]; start = 6; end = 16;}
        else if(position>15&&position<20) { d4 = Constant.driver_names[position]; start = 16; end = 20;}
        else if(position>19&&position<30) { d3 = Constant.driver_names[position-14]; start = 20; end = 30;}
        for (int i = start; i < end; i++) {
            rl_dm[i].setBackgroundResource(R.drawable.ic_select_off);
        }   rl_dm[position].setBackgroundResource(R.drawable.ic_select_on);
    }



    //** FRAGMENT-DRAWER **//
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.n_home) {
            setFragment(new Tab0Home(), getString(R.string.td_main),"");
        } else if (id == R.id.n_news) {
            setFragment(new TabBrowser(), getString(R.string.td_news),"");
        } else if (id == R.id.n_drivers) {
            setFragment(new Tab2Drivers(), getString(R.string.td_drivers),"");
        } else if (id == R.id.n_stats) {
            setFragment(new Tab3Stats(), getString(R.string.td_stats),"");
        } else if (id == R.id.n_guide) {
            setFragment(new TabBrowser(), getString(R.string.td_guide), getString(R.string.link_guide));
        } else if (id == R.id.n_rules) {
            setFragment(new TabBrowser(), getString(R.string.td_rules), getString(R.string.link_rules));
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void setFragment(Fragment tab, String home, String link) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fl_main, tab)
                .commit();
        toolbar.setTitle(home);
        Bundle bundle = new Bundle();
        bundle.putString("link", link);
        tab.setArguments(bundle);
    }

    //** ACTIVITY **//
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem shareItem = menu.findItem(R.id.action_calc);
        if(!key.equals("")) {
            if (key.substring(0, key.length() - 4).equals(Config.getKey())) {
                shareItem.setVisible(true);
            }
        }
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_info) {
            startActivity(new Intent(MainActivity.this, InfoActivity.class));
            return true;
        } else if(id == R.id.action_calc) {
            startActivity(new Intent(MainActivity.this, CalcActivity.class));
            return true;
        } else if(id == R.id.action_update) {
            final ProgressDialog pdialog = ProgressDialog.show(MainActivity.this, "",
                    getString(R.string.pg_deletedata), true);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            preferences.edit().remove("d1").commit();
            preferences.edit().remove("d2").commit();
            preferences.edit().remove("d3").commit();
            preferences.edit().remove("d4").commit();
            preferences.edit().remove("contents").commit();
            preferences.edit().remove("gpdatas").commit();
            preferences.edit().remove("gpgone").commit();

            new Handler().postDelayed(() -> {
                pdialog.setMessage(getString(R.string.pg_restartapp));
                new Handler().postDelayed(() -> {
                    pdialog.dismiss();
                    PackageManager packageManager = context.getPackageManager();
                    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
                    ComponentName componentName = intent.getComponent();
                    Intent mainIntent = IntentCompat.makeRestartActivityTask(componentName);
                    context.startActivity(mainIntent);
                    System.exit(0);
                }, 750);
            }, 1100);


            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}