package com.b2lmobitech.spottest;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.TabLayout;
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.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

import com.b2lmobitech.spottest.adapter.HistoryAdapter;
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.util.HashMap;
import java.util.Map;

public class HistoryActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    LinearLayout noHistoryLayout;
    String groupId="";

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

        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        noHistoryLayout=findViewById(R.id.noHistoryLayout);
        noHistoryLayout.setVisibility(View.GONE);

        getSupportActionBar().setTitle("History");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setElevation(0f);
        if(getIntent().getStringExtra("groupId")!=null) {
            groupId = getIntent().getStringExtra("groupId");
        }
        groupId = "All";//Swathi,used to show 'user' records of his belonging groups only
        addTabs();
        getTests("completed");

    }

    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"));

        tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                noHistoryLayout.setVisibility(View.GONE);
                 if(tab.getPosition()==0){
                    getTests("completed");
                }else if(tab.getPosition()==1){
                    getTests("missed");
                }
            }

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

            }

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

            }
        });
    }

    private void getTests(String type) {

        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.addToQueue(URL.GET_HISTORY, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                try {
                    setTests(new JSONObject(response));
                } 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);
        }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()){
                            alertExameActive();
                       }else if(!MyRequestQueue.getInstance(HistoryActivity.this).isNoNetwork()){
                           if(!PermissionSingleton.getInstance(HistoryActivity.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);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    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();
    }

}
