package com.b2lmobitech.spottest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.b2lmobitech.spottest.adapter.ItemSelectedListener;
import com.b2lmobitech.spottest.adapter.SectionAdapter;
import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.service.MoniterService;
import com.b2lmobitech.spottest.sql.DataBase;
import com.b2lmobitech.spottest.utils.MySnackbar;
import com.b2lmobitech.spottest.utils.Preference;
import com.b2lmobitech.spottest.utils.Utility;

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

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

public class MockTestActivity extends AppCompatActivity {

    String assignId;
    JSONArray sectionsArray;
    Handler handler = new Handler();
    private TextView timerText;
    int starttime=0;
    ImageView snapshot,timerIcon;
    TextView alertText;
    RecyclerView recyclerView;
    private NestedScrollView nestedScrollView;
    int alert1=-1,alert2=-1;
    MyRequestQueue myRequestQueue;
    private Context mycontext;


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

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

        Button submit_buttonsection =  findViewById(R.id.submit_buttonsection);
        mycontext = this;

        assignId =getIntent().getStringExtra("assignid");
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        getWidgets();
        getSections();
        startService();
        submit_buttonsection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MySnackbar.getInstance(MockTestActivity.this).dismiss();
                showResult();
            }
        });
    }

    private void startService(){
        Intent intent=new Intent(getApplicationContext(), MoniterService.class);
        startService(intent);
    }

    private void getWidgets(){
        recyclerView=findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        snapshot=findViewById(R.id.snapshot);
        timerIcon=findViewById(R.id.timerIcon);
        alertText=findViewById(R.id.alertText);

        findViewById(R.id.signCameraLayout).setVisibility(View.GONE);

        nestedScrollView=findViewById(R.id.scrollView);
        nestedScrollView.setVisibility(View.GONE);
        timerText=findViewById(R.id.timerText);

        DataBase dataBase=new DataBase(this);
        dataBase.deleteAnswered(assignId);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        try {
            setSectiosAdapter();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getSections() {

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("assignId", assignId);
        myRequestQueue=MyRequestQueue.getInstance(this);
        myRequestQueue.showProgressBar();
        myRequestQueue.addToQueueWithoutProgress(URL.GET_SECTIONS_MOCK, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {

                try {
                    setSections(new JSONObject(response));
                    getQuestions();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getQuestions() {
        final DataBase dataBase=new DataBase(this);
        if(dataBase.isQuestionsAlreadyExists(assignId)){
            getOptions();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("assignId", assignId);
        myRequestQueue.addToQueueWithoutProgress(URL.GET_QUESTIONS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {

                getOptions();

                try {
                    JSONArray questionsArray=new JSONObject(response).getJSONArray("questions");
                    for(int i=0; i<questionsArray.length(); i++){
                        dataBase.insertQuestion(questionsArray.getJSONObject(i));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getOptions() {
        final DataBase dataBase=new DataBase(this);
        if(dataBase.isOptionsAlreadyExists(assignId)){
            getAnswers();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("assignId", assignId);
        myRequestQueue.addToQueueWithoutProgress(URL.GET_OPTIONS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                getAnswers();
                try {
                    JSONArray optionsArray=new JSONObject(response).getJSONArray("options");
                    for(int i=0; i<optionsArray.length(); i++){
                        dataBase.insertOptions(optionsArray.getJSONObject(i),assignId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getAnswers() {
        final DataBase dataBase=new DataBase(this);
        if(dataBase.isAnwsersAlreadyExists(assignId)){
            myRequestQueue.hideProgressBar();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(this).getStudentId());
        params.put("assignId", assignId);
        myRequestQueue.addToQueueWithoutProgress(URL.GET_ANSWERS, params, new MyRequestQueue.MyRequestFinishedListener() {
            @Override
            public void requestResult(String response) {
                myRequestQueue.hideProgressBar();
                try {
                    JSONArray optionsArray=new JSONObject(response).getJSONArray("answers");
                    for(int i=0; i<optionsArray.length(); i++){
                        dataBase.insertReference(optionsArray.getJSONObject(i),assignId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void startTimer(final int maxSeconds){
        starttime=maxSeconds;
        timerText.setVisibility(View.VISIBLE);
        timerIcon.setVisibility(View.VISIBLE);
        handler.post(new Runnable() {
            @Override
            public void run() {
                starttime=starttime-1;
                Intent intent=new Intent("spottest.timer.mock");

                if(starttime!=0) {
                    intent.putExtra("timer", Utility.getMinitues(starttime));
                    handler.postDelayed(this, 1000);
                }else{
                    intent.putExtra("timer","0");
                    intent.putExtra("submit",Utility.getMinitues(starttime));
                    sendBroadcast(intent);
                    handler.removeCallbacks(this);

                }

                if(alert1!=-1 && alert2!=-1) {
                    if (starttime == alert1) {
                        intent.putExtra("alert", true);
                        intent.putExtra("text", "Half time over");
                    } else if (starttime == alert2) {
                        intent.putExtra("alert", true);
                        intent.putExtra("text", "Only 5 minutes remaining");
                    }
                }
                sendBroadcast(intent);
            }
        });
    }


    //In this function update assign id as per received from server

    private void setSections(final JSONObject jsonObject) throws JSONException {


        assignId=jsonObject.getString("assignId");

        final DataBase dataBase=new DataBase(this);
        dataBase.deleteAnswered(assignId);

        sectionsArray=jsonObject.getJSONArray("sections");

       // JSONObject dataObject=jsonObject.getJSONObject("test");

        int diff=jsonObject.getInt("diff");

        if(diff>0) {
            startTimer(diff);
            alertText.setVisibility(View.GONE);
        }else{
            timerText.setVisibility(View.GONE);
            timerIcon.setVisibility(View.GONE);
            alertText.setVisibility(View.VISIBLE);
        }
        alert1=jsonObject.getInt("alert1");
        alert2=jsonObject.getInt("alert2");


        setSectiosAdapter();


        /*if(diff<0){
            findViewById(R.id.signCameraLayout).setVisibility(View.GONE);
            getSupportActionBar().setTitle("Preview");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }else{
            findViewById(R.id.signCameraLayout).setVisibility(View.VISIBLE);
        }*/


    }

    private void setSectiosAdapter() throws JSONException {

        DataBase dataBase=new DataBase(this);
        for(int i=0; i<sectionsArray.length(); i++){
            sectionsArray.getJSONObject(i).put("answered",dataBase.getAnswers(
                    sectionsArray.getJSONObject(i).getString("section_id"),assignId).size());
        }

        SectionAdapter sectionAdapter=new SectionAdapter(getApplicationContext(),sectionsArray, new ItemSelectedListener() {
            @Override
            public void selected(int position) {
                try {
                    Intent intent=new Intent(getApplicationContext(),QuestionsActivity.class);
                    intent.putExtra("preview",sectionsArray.getJSONObject(position).getInt("answered")!=0);
                    intent.putExtra("section",sectionsArray.getJSONObject(position).getString("section_id"));
                    intent.putExtra("assignId",assignId);
                    intent.putExtra("mock",true);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },true);

        recyclerView.setAdapter(sectionAdapter);
        nestedScrollView.setVisibility(View.VISIBLE);
    }

    private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(timerText!=null) {
                timerText.setText(intent.getStringExtra("timer"));
            }
            if(getIntent().getBooleanExtra("submit",false)){
                timerText.setVisibility(View.GONE);
                timerIcon.setVisibility(View.GONE);
                alertSubmit();
            }

            if(intent.getBooleanExtra("alert",false)){
                alert(intent.getStringExtra("text"));
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(broadcastReceiver,new IntentFilter("spottest.timer.mock"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
    }

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

// Add the buttons
        builder.setPositiveButton("SHOW RESULT", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                showResult();
            }
        });

        builder.setTitle("Time Out");
        builder.setMessage("Given time limit has been reached");
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(getApplicationContext(),MoniterService.class));
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_mock, 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.done) {
            MySnackbar.getInstance(this).dismiss();
            showResult();
        }

        return super.onOptionsItemSelected(item);
    }

    private void showResult(){
        stopService(new Intent(getApplicationContext(),MoniterService.class));
        Intent intent=new Intent(getApplicationContext(),MockResultActivity.class);
        intent.putExtra("json",sectionsArray.toString());
        intent.putExtra("assignId",assignId);
        startActivity(intent);
        finish();
    }

    private void alert(String string){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);



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

        builder.setMessage(string);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }

}
