package com.b2lmobitech.spottest;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.VpnService;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.b2lmobitech.spottest.adapter.HistoryAdapter;
import com.b2lmobitech.spottest.adapter.ItemSelectedListener;
import com.b2lmobitech.spottest.adapter.TestsAdapter;
import com.b2lmobitech.spottest.frags.AccessAlerFragment;
import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.service.BlackHoleService;
import com.b2lmobitech.spottest.service.MoniterService;
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.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class TestActivity extends AppCompatActivity {

    String groupId;
    RecyclerView recyclerView;
    TextView viewHistory;
    ImageView NoHistoryicon;
    TextView NoHistorytext;
    LinearLayout noHistoryLayout;
    MyRequestQueue myRequestQueue;
    SwipeRefreshLayout swipelayout;
    JSONObject selectedTestObject;
    private  int tab_pos;

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

        groupId=getIntent().getStringExtra("group_id");
        recyclerView=findViewById(R.id.recyclerView);
//        viewHistory=findViewById(R.id.viewHistory);
        noHistoryLayout=findViewById(R.id.noHistoryLayout);
        NoHistoryicon=findViewById(R.id.noHistoryicon);
        NoHistorytext=findViewById(R.id.noHistory);
        noHistoryLayout.setVisibility(View.GONE);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        getSupportActionBar().setTitle(getIntent().getStringExtra("name"));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//        viewHistory.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                openHistory();
//            }
//        });

        swipelayout=findViewById(R.id.swipelayout);
        swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getTests();
            }
        });
        //--swathi--
        tab_pos =0 ;
        getSupportActionBar().setElevation(0f);
        addTabs();
        //--swathi--

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(tab_pos == 0 ) {
            myRequestQueue = MyRequestQueue.getInstance(this);
            getTests();
        }
    }

    private void getTests() {
//        //--swathi--
//        Toast.makeText(this,"email="+Preference.getInstance(this).getStudentId(),Toast.LENGTH_SHORT).show();
//        Toast.makeText(this,"groupid="+groupId,Toast.LENGTH_SHORT).show();
//        //--swathi--
        if (!swipelayout.isRefreshing()) {
            myRequestQueue.showProgressBar();
            noHistoryLayout.setVisibility(View.GONE);
        }

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("groupId",groupId);
        myRequestQueue.addToQueueWithoutProgress(URL.GET_TESTS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    setTestAdapter(new JSONObject(response));
                    myRequestQueue.hideProgressBar();
                    if(swipelayout.isRefreshing()){
                        swipelayout.setRefreshing(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setTestAdapter(final JSONObject jsonObject) throws JSONException {
        final JSONArray testsArray=jsonObject.getJSONArray("tests");

        if(testsArray.length()==0){
            noHistoryLayout.setVisibility(View.VISIBLE);
            NoHistoryicon.setImageResource(R.drawable.ic_event);
            NoHistorytext.setText("No Assigned Tests");
//            //--swathi--
//            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//            Long currentTime2 = Calendar.getInstance().getTimeInMillis();
//            Long savedtime = prefs.getLong("vpnstarttime", 0);
//            if(savedtime!=0) {
//                Date date = new Date(savedtime);
//                Date date2 = new Date(currentTime2);
//                Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
//                Toast.makeText(getApplicationContext(), "savedtime=" + format.format(date), Toast.LENGTH_SHORT).show();
//                Toast.makeText(getApplicationContext(), "currentTime=" + format.format(date2), Toast.LENGTH_SHORT).show();
//                Toast.makeText(getApplicationContext(), "difference=" + (currentTime2 - savedtime), Toast.LENGTH_SHORT).show();
//                if ((currentTime2 - savedtime) >= (5 * 60 * 1000)) {
//                    stopService(new Intent(getApplicationContext(), MoniterService.class));
//                    prefs.edit().putLong("vpnstarttime", 0).commit();
//                }
//
//            }
//            //--swathi--
            //stopService(new Intent(getApplicationContext(), MoniterService.class));

        }else{
            noHistoryLayout.setVisibility(View.GONE);
        }

        TestsAdapter testsAdapter=new TestsAdapter(testsArray, new ItemSelectedListener() {
            @Override
            public void selected(int position) {
                try {
                    if(isNetworkAvailable()) {
                        selectedTestObject = testsArray.getJSONObject(position);
                        checkVPN();
                    }
                    else
                    {
                        Toast.makeText(TestActivity.this,"It seems you are not connected to network,please enable it.",Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        testsAdapter.setInfoSelectedListener(new TestsAdapter.InfoSelectedListener() {
            @Override
            public void showInfo(String assignId) {

                //startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(assignId)));
                Intent intent = new Intent(getApplicationContext(), WebActivity.class);
                intent.putExtra("url",assignId);
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(testsAdapter);

    }

    private void checkVPN(){

        Intent prepare = VpnService.prepare(this);
        if (prepare == null) {
            onActivityResult(REQUEST_VPN, RESULT_OK, null);
        } else {
            try {
                startActivityForResult(prepare, REQUEST_VPN);
            } catch (Throwable ex) {
                onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
            }
        }
    }

    private void nextActivity(){

        try {
            if(selectedTestObject.getString("completed").equals("null") ){
                if(selectedTestObject.getBoolean("canStart")) {
                    startExam(selectedTestObject.getString("exam_schedule_id"));
                }else{
                    Intent intent = new Intent(getApplicationContext(), PreviewActivity.class);
                    intent.putExtra("assignid", selectedTestObject.getString("exam_schedule_id"));
                    startActivity(intent);
                }
            }else if(!selectedTestObject.getString("start_type").equals("android")){
                alertExameActive();
            }else {
                if(!MyRequestQueue.getInstance(TestActivity.this).isNoNetwork()){
                    if(!PermissionSingleton.getInstance(TestActivity.this).isUsageAccessAccessGranted()){
                        new AccessAlerFragment().showNow(getSupportFragmentManager(),"");
                    }else {
                        //--swathi--//
                        SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("assignid", selectedTestObject.getString("exam_schedule_id"));
                        editor.apply();
                        //--swathi--//
                        startExam(selectedTestObject.getString("exam_schedule_id"));//24 sep changed
//                        Intent intent = new Intent(getApplicationContext(), SectionsActivity.class);
//                        intent.putExtra("assignid", selectedTestObject.getString("exam_schedule_id"));
//                        startActivity(intent);
//                        Toast.makeText(TestActivity.this,"else case",Toast.LENGTH_LONG).show();
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void startExam(final String exam){

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("examId",exam);

        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueue(URL.START, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {

                try {
                    JSONObject jsonObject=new JSONObject(response);
//                    Toast.makeText(TestActivity.this,"s="+jsonObject.getInt("s"),Toast.LENGTH_LONG).show();
                    if(jsonObject.getInt("s")==1) {
                        //--swathi--//
                        SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("assignid", exam);
                        editor.apply();
                        //--swathi--//
                        Intent intent = new Intent(getApplicationContext(), SectionsActivity.class);
                        intent.putExtra("assignid", exam);
                        startActivity(intent);
                    }else if(jsonObject.getInt("s")==1){
                        alertExameActive();
                    }
                    else if(jsonObject.getInt("s")==3){
                        alertexamcompleted();
                    }
                    else{
                        Toast.makeText(getApplicationContext(),"Unable to Start",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }

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

        if(groupId.equals("null")){
            menu.findItem(R.id.members).setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.members) {
           Intent intent=new Intent(getApplicationContext(),MembersActivity.class);
           intent.putExtra("groupId",groupId);
           startActivity(intent);
        }else if(item.getItemId()==android.R.id.home){
            onBackPressed();
        }
//        else if(item.getItemId()==R.id.history){
//            openHistory();
//        }
        return super.onOptionsItemSelected(item);
    }

    private void openHistory(){
        Intent intent=new Intent(getApplicationContext(),HistoryActivity.class);
        intent.putExtra("groupId",groupId);
        startActivity(intent);
    }

    private static final int REQUEST_VPN = 1;

    private void StartVPN(){
        String TAG="VPN TEST";
        Intent prepare = VpnService.prepare(getApplicationContext());
        if (prepare == null) {
            onActivityResult(REQUEST_VPN, RESULT_OK, null);
        } else {
            try {
                startActivityForResult(prepare, REQUEST_VPN);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                onActivityResult(REQUEST_VPN, RESULT_CANCELED, null);
                Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_VPN) {
            // Update enabled state
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            prefs.edit().putBoolean("enabled", resultCode == RESULT_OK).apply();

            // Start service
            if (resultCode == RESULT_OK) {
//                //---swathi--
//                Long currentTime = Calendar.getInstance().getTimeInMillis();
//                prefs.edit().putLong("vpnstarttime", currentTime).commit();
//                //---swathi--
                BlackHoleService.start(this);
                nextActivity();
            }else{
                Toast.makeText(getApplicationContext(),"Please enable VPN",Toast.LENGTH_SHORT).show();
            }
        } else
            super.onActivityResult(requestCode, resultCode, data);

    }

    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.setTitle(R.string.alertPlatformTitle);
        builder.setMessage(R.string.alertPlatform);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
////--swathi--
//    @Override
//    protected void onStart() {
//        super.onStart();
//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//        Long currentTime2 = Calendar.getInstance().getTimeInMillis();
//        Long savedtime = prefs.getLong("vpnstarttime", 0);
//        if(savedtime!=0)
//        {
//            Date date = new Date(savedtime);
//            Date date2 = new Date(currentTime2);
//            Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
//            Toast.makeText(getApplicationContext(),"savedtime="+format.format(date),Toast.LENGTH_SHORT).show();
//            Toast.makeText(getApplicationContext(),"currentTime="+format.format(date2),Toast.LENGTH_SHORT).show();
//            Toast.makeText(getApplicationContext(),"difference="+(currentTime2 - savedtime),Toast.LENGTH_SHORT).show();
//            if((currentTime2 - savedtime) >= (5*60*1000))
//            {
//                stopService(new Intent(getApplicationContext(), MoniterService.class));
//                    prefs.edit().putLong("vpnstarttime", 0).commit();
//            }
//        }
//
//    }
//    //--swathi--
//    //--swathi--
private void addTabs(){
    TabLayout tabLayout=findViewById(R.id.tabLayout);
    tabLayout.addTab(tabLayout.newTab().setText("Schedule"),true);
    tabLayout.addTab(tabLayout.newTab().setText("Completed"));
    tabLayout.addTab(tabLayout.newTab().setText("Missed"));
//    //--swathi--
//    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
//    final PagerAdapter adapter = new PagerAdapter
//            (getSupportFragmentManager(), tabLayout.getTabCount()) {
//        @Override
//        public int getCount() {
//            return 0;
//        }
//
//        @Override
//        public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
//            return false;
//        }
//    };
//    viewPager.setAdapter(adapter);
//    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//    //--swathi--
    tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
//            viewPager.setCurrentItem(tab.getPosition());
            tab_pos = tab.getPosition();
            noHistoryLayout.setVisibility(View.GONE);
            if(tab.getPosition()==0){
                getTests();
                swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        getTests();
                    }
                });
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        Uri imageUri = getOutputMediaFileUri();
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
////        startActivityForResult(intent, 1);
//            startActivityForResult(intent, 100);
//        startActivity(intent);
            }
            else if(tab.getPosition()==1){
                swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                         getTests("completed");
                    }
                });
                getTests("completed");
            }else if(tab.getPosition()==2){
                swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                       getTests("missed");
                    }
                });
                getTests("missed");
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}
//    private Uri getOutputMediaFileUri()
//        {
//        File mediaFile = null;
//        File mediaStorageDir = new File("/sdcard/Android/data/com.b2lmobitech.spottest/"+"Spottestimages");
//        if(!mediaStorageDir.exists())
//        {
//            if(!mediaStorageDir.mkdirs())
//            {
//              return  null;
//            }
//        }
//        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
//                Locale.getDefault()).format(new Date());
//        mediaFile = new File(mediaStorageDir.getPath() + File.separator
//
//                + "IMG_" + System.currentTimeMillis() + ".jpg");//timeStamp
//        try {
//            //mediaFile.getParentFile().mkdirs();
//            mediaFile.createNewFile();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//
//            return  FileProvider.getUriForFile(getApplicationContext(),
//                    BuildConfig.APPLICATION_ID + ".provider",
//                    mediaFile);//getActivity()
//
////            Log.e("Androdid", "n");
//        } else {
//            return Uri.fromFile(mediaFile);
////            Log.e("Androdid", "below n");
//        }
//        //  uri= Uri.fromFile(mediaFile);
//
//
//    }

    private void getTests(String type) {
        if (!swipelayout.isRefreshing()) {
            myRequestQueue.showProgressBar();
            noHistoryLayout.setVisibility(View.GONE);
        }
        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("type",type);
        params.put("groupId",groupId);

//        MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.addToQueueWithoutProgress(URL.GET_HISTORY, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    setTests(new JSONObject(response));
                    myRequestQueue.hideProgressBar();
                    if(swipelayout.isRefreshing()){
                        swipelayout.setRefreshing(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void setTests(JSONObject jsonObject) throws JSONException {
        final JSONArray testsArray=jsonObject.getJSONArray("tests");

        if(testsArray.length()==0){
            noHistoryLayout.setVisibility(View.VISIBLE);
            NoHistoryicon.setImageResource(R.drawable.ic_history);
            NoHistorytext.setText("No History");
        }else{
            noHistoryLayout.setVisibility(View.GONE);
        }

        HistoryAdapter testsAdapter=new HistoryAdapter(testsArray, new ItemSelectedListener() {
            @Override
            public void selected(int position) {
                try {
                    JSONObject testObject=testsArray.getJSONObject(position);
                    if(testObject.getString("completed").equals("yes")){
                        Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
                        intent.putExtra("assignid", testObject.getString("exam_schedule_id"));
                        startActivity(intent);
                    }else {
                        if(Preference.getInstance(getApplicationContext()).getExamStatus()){
                            alertExameActive2();
                        }else if(!MyRequestQueue.getInstance(TestActivity.this).isNoNetwork()){
                            if(!PermissionSingleton.getInstance(TestActivity.this).isUsageAccessAccessGranted()){
                                new AccessAlerFragment().showNow(getSupportFragmentManager(),"");
                            }else {
                                Intent intent = new Intent(getApplicationContext(), MockTestActivity.class);
                                intent.putExtra("assignid", testObject.getString("exam_schedule_id"));
                                startActivity(intent);
                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        recyclerView.setAdapter(testsAdapter);
    }
    private void alertExameActive2(){
        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();
    }
////--swathi--
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(TestActivity.this.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
    private void alertexamcompleted(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setNegativeButton("OK" +
                "", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                myRequestQueue = MyRequestQueue.getInstance(TestActivity.this);
                getTests();
            }
        });
        builder.setTitle(R.string.alertPlatformTitle);
        builder.setMessage(R.string.alertcompleted);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
