package com.b2lmobitech.spottest;

import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.b2lmobitech.spottest.adapter.GroupsAdapter;
import com.b2lmobitech.spottest.adapter.ItemSelectedListener;
import com.b2lmobitech.spottest.frags.AccessAlerFragment;
import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.utils.PermissionSingleton;
import com.b2lmobitech.spottest.utils.Preference;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class DashboardActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    RecyclerView recyclerView;
    TextView noHistory;
    private String build_code,versionname,installedtime,versioncode,updatedtime;
//    //--swathi--
//    float[] hsv;
//    int runColor;
//    LinearLayout Layoutback;

//    //--swathi--
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        if(!MyRequestQueue.getInstance(this).isNoNetwork()) {
            get_currentversion();
        }
        getWigets();
        setDrawer();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getGroups();
    }

    private void getWigets(){
        recyclerView=findViewById(R.id.recyclerView);
        noHistory=findViewById(R.id.noHistory);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
    }

    private void setDrawer(){

        Toolbar toolbar =  findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        TextView idText=navigationView.getHeaderView(0).findViewById(R.id.idText);
        TextView nameText=navigationView.getHeaderView(0).findViewById(R.id.nameText);

        idText.setText(Preference.getInstance(this).getString("reg_no"));
        nameText.setText(Preference.getInstance(this).getName());
//        //--swathi--
        LinearLayout Layoutback=navigationView.getHeaderView(0).findViewById(R.id.navside_full);
        Layoutback.setBackgroundColor(Color.parseColor("#29AB87"));
        navigationView.setItemIconTintList(null);
//        ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
//        anim.setDuration(2000);
//
//
//        int hue = 0;
//        hsv = new float[3]; // Transition color
//        hsv[1] = 1;
//        hsv[2] = 1;
//        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//
//                hsv[0] = 360 * animation.getAnimatedFraction();
//
//                runColor = Color.HSVToColor(hsv);
//                Layoutback.setBackgroundColor(runColor);
//            }
//        });
//
//        anim.setRepeatCount(Animation.INFINITE);
//
//        anim.start();
//        //--swathi---

    }

    private void getGroups(){
        noHistory.setVisibility(View.GONE);
        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());

        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.GET_GROUPS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    setGroups(new JSONObject(response));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void setGroups(final JSONObject jsonObject) throws JSONException {
        final JSONArray jsonArray=jsonObject.getJSONArray("groups");

        if(jsonArray.length()==0){
            noHistory.setVisibility(View.VISIBLE);
        }else{
            noHistory.setVisibility(View.GONE);
        }
        GroupsAdapter groupsAdapter=new GroupsAdapter(jsonArray, new ItemSelectedListener() {
            @Override
            public void selected(int position) {
                Intent intent=new Intent(getApplicationContext(),TestActivity.class);
                try {
                    JSONObject object=jsonArray.getJSONObject(position);
                    intent.putExtra("group_id",object.getString("group_id"));
                    intent.putExtra("name",object.getString("group_name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(groupsAdapter);
    }

    @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.dashboard, menu);
        return true;
    }

    @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_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }*/

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if(id==R.id.history){
            if(!MyRequestQueue.getInstance(this).isNoNetwork()) {
                startActivity(new Intent(getApplicationContext(), HistoryActivity.class));
            }
        }
         if(id==R.id.logOut) {
            if (Preference.getInstance(getApplicationContext()).getExamStatus()) {
                alertExameActive();
            } else{
                alertLogout();
            }
        }else if(id==R.id.mock){
            if(Preference.getInstance(getApplicationContext()).getExamStatus()){
                alertExameActive();
            }else if(!MyRequestQueue.getInstance(this).isNoNetwork()){
                if(!PermissionSingleton.getInstance(this).isUsageAccessAccessGranted()){
                    new AccessAlerFragment().showNow(getSupportFragmentManager(),"");
                }else {
                    Intent intent = new Intent(getApplicationContext(), MockTestActivity.class);
                    //assign id is empty to remind that this is a mock test
                    intent.putExtra("assignid", "mock");
                    startActivity(intent);
                }
            }
        }else if(id==R.id.aboutUs){
            Intent intent=new Intent(getApplicationContext(),AboutUsActivity.class);
            startActivity(intent);
        }
         else if(id==R.id.privacy){
             Intent intent = new Intent(getApplicationContext(), WebActivity.class);
             intent.putExtra("url", "http://Www.fieldcloud.in/spottest/term_condition/Privacy.html");
             startActivity(intent);
         }
         else if(id==R.id.terms){
             Intent intent = new Intent(getApplicationContext(), WebActivity.class);
             intent.putExtra("url", "http://Www.fieldcloud.in/spottest/term_condition/Terms.html");
             startActivity(intent);
         }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void alertLogout(){

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
        builder.setPositiveButton("LOG OUT", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                getSharedPreferences(BuildConfig.APPLICATION_ID,MODE_PRIVATE).edit().clear().apply();
                Intent intent=new Intent(DashboardActivity.this,SplashActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        });

        builder.setNegativeButton("CANCEL" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });

        builder.setTitle("Log Out");
        builder.setMessage("Are you sure you want to log out?");
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void alertExameActive(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setNegativeButton("OK" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });
        builder.setMessage(R.string.alertExam);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
private void get_currentversion()
{
    build_code = "";
    versionname = "";
    installedtime = "";
    versioncode = "";
    updatedtime = "";
    try {
        PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        long firstinstalltime = packageInfo.firstInstallTime;
        long lastupdateime = packageInfo.lastUpdateTime;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        build_code = "sdk " + Build.VERSION.SDK_INT;
        versionname = String.valueOf(packageInfo.versionName);
        installedtime = dateFormat.format(new Date(firstinstalltime));
        updatedtime = dateFormat.format(new Date(lastupdateime));
        versioncode = String.valueOf(packageInfo.versionCode);
       // Toast.makeText(DashboardActivity.this,"shr_current_versionname = "+Preference.getInstance(this).getversionname(),Toast.LENGTH_LONG).show();
//                 Toast.makeText(LoginActivity.this,"current_versionname = "+jsonObject.getString("current_versionname"),Toast.LENGTH_LONG).show();
//                Toast.makeText(LoginActivity.this,"updated_time = "+jsonObject.getString("updated_time"),Toast.LENGTH_LONG).show();
        if (!versionname.equalsIgnoreCase(Preference.getInstance(this).getversionname()) || !updatedtime.equalsIgnoreCase(Preference.getInstance(this).getupdatedtime())) {// || !firebase_token.equalsIgnoreCase(FirebaseInstanceId.getInstance().getToken()
            updateCurrentVerision();
        }
    } catch (PackageManager.NameNotFoundException e) {
        //e.printStackTrace();
    }
}
    private void updateCurrentVerision() {
        Map<String, String> params = new HashMap<>();
        params.put("reg_no",Preference.getInstance(this).getreg_no());
        params.put("installed_time", installedtime);
        params.put("updated_time", updatedtime);
        params.put("current_versionname", versionname);
        params.put("current_versioncode", versioncode);
        params.put("build_code", build_code);
        MyRequestQueue myRequestQueue = MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.UPDATE_CURRENTVERSION, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                JSONObject json = null;
                try {
                    json = new JSONObject(response);
                    if(json.getInt("success")==1){
                        Preference preference=Preference.getInstance(DashboardActivity.this);
                        preference.putString("installed_time",installedtime);
                        preference.putString("updated_time",updatedtime);
                        preference.putString("current_versionname",versionname);
                        preference.putString("current_versioncode",versioncode);
                        preference.putString("build_code",build_code);
//                        Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
                        finish();
                    }else{
//                        Toast.makeText(getApplicationContext(),json.getString("message"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }
}
