package in.ac.iitm.students.activities.treasurehunt;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.squareup.picasso.Picasso;

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

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import in.ac.iitm.students.R;
import in.ac.iitm.students.activities.AboutUsActivity;
import in.ac.iitm.students.activities.main.CameraActivity;
import in.ac.iitm.students.activities.main.HomeActivity;
import in.ac.iitm.students.fragments.CameraFragment;
import in.ac.iitm.students.objects.Clue;
import in.ac.iitm.students.objects.ClueList;
import in.ac.iitm.students.others.LogOutAlertClass;
import in.ac.iitm.students.others.LogUtils;
import in.ac.iitm.students.others.MySingleton;
import in.ac.iitm.students.others.UtilStrings;
import in.ac.iitm.students.others.Utils;

public class QuestionsActivity extends AppCompatActivity {

    static final int MY_PERMISSION_REQUEST_CAMERA = 1024;
    static final int MY_PERMISSION_REQUEST_WRITE_STORAGE = 2048;
    static final int MY_PERMISSION_REQUEST_READ_STORAGE = 512;

    TextView countdown;
    SwipeRefreshLayout srl;
    int returned_status;
    SharedPreferences pref;
    ProgressDialog progressDialog;

    ArrayList<Button> buttonArrayList;
    ArrayList<Button> skipArrayList;
    ArrayList<String> clues;
    ArrayList<Integer> clueIds;
    ArrayList<Clue> clueArrayList;
    ArrayList<TextView> textViews;
    ArrayList<ImageView> imageViews;
    ArrayList<View> cards;
    int submit_perm_index;


    int batch;
    int cardCount;

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

        pref = getBaseContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
        if (pref.getAll().containsKey(UtilStrings.TIMESTAMP)) {
            Utils.setup_drawer(this, R.id.drawer_layout, R.id.nav_view, R.id.toolbar, R.id.nav_treasure_hunt, 1);
        } else {
            Utils.setup_drawer(this, R.id.drawer_layout, R.id.nav_view, R.id.toolbar, R.id.nav_treasure_hunt, 0);
        }

        batch = Utils.getprefInt(UtilStrings.BATCH_NUM, getBaseContext());
        cardCount = getCountForBatch(batch);
        submit_perm_index = 0;

        clues = new ArrayList<>();
        clueIds = new ArrayList<>();
        clueArrayList = new ArrayList<>();
        textViews = new ArrayList<>();
        imageViews = new ArrayList<>();
        cards = new ArrayList<>();
        buttonArrayList = new ArrayList<>();
        skipArrayList = new ArrayList<>();

        for (int i = 0; i < cardCount; i++) {
            clues.add(" ");
            clueIds.add(0);
            clueArrayList.add(new Clue());
        }
        cards.add(findViewById(R.id.card_q_1));
        cards.add(findViewById(R.id.card_q_2));
        cards.add(findViewById(R.id.card_q_3));
        cards.add(findViewById(R.id.card_q_4));

        for (int i = 0; i < 4; i++) {
            textViews.add((TextView) cards.get(i).findViewById(R.id.tv_question));
            imageViews.add((ImageView) cards.get(i).findViewById(R.id.img_question));
            buttonArrayList.add((Button) cards.get(i).findViewById(R.id.ans_submit));
            skipArrayList.add((Button) cards.get(i).findViewById(R.id.ans_skip));
            cards.get(i).setVisibility(View.VISIBLE);
        }

        if (batch > 3) setSkipInvisible();
        else setSkipVisible();

        returned_status = -2;

        Button answers = findViewById(R.id.btn_answer_activity);
        answers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), AnswersActivity.class);
                startActivity(intent);
            }
        });

        ImageButton refresh = (ImageButton)findViewById(R.id.btn_refresh);
        refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshQuestions();
            }
        });



        countdown = findViewById(R.id.timer);
        Long login = Utils.getprefLong(UtilStrings.TIMESTAMP, getBaseContext());
        LogUtils.debug("timelogin", login.toString());
        Long zerohours = 0L;
        Long timeOfActivity = System.currentTimeMillis();
        new CountDownTimer(zerohours - timeOfActivity + login, 1000) {

            public void onTick(long millisUntilFinished) {
                long d = millisUntilFinished;
                long hours = TimeUnit.MILLISECONDS.toHours(d);
                d -= TimeUnit.HOURS.toMillis(hours);
                long minutes = TimeUnit.MILLISECONDS.toMinutes(d);
                d -= TimeUnit.MINUTES.toMillis(minutes);
                long seconds = TimeUnit.MILLISECONDS.toSeconds(d);
                countdown.setText(hours + ":" + minutes + ":" + seconds);
            }

            public void onFinish() {

                countdown.setText("00:00:00");
                countdown.setTextColor(getResources().getColor(R.color.red));
            }
        }.start();


        srl = findViewById(R.id.scroll_view_q);
        srl.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        // This method performs the actual data-refresh operation.
                        // The method calls setRefreshing(false) when it's finished.
                        refreshQuestions();
                        srl.setRefreshing(false);
                    }
                }
        );

        for (int i = 0; i < 4; i++) {
            skipArrayList.get(i).setEnabled(true);
            final int finalI = i;
            skipArrayList.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setSkipped(clueIds.get(finalI));
                }
            });
        }
//        if(ContextCompat.checkSelfPermission(this, Manifest.permission_group.STORAGE) != PackageManager.PERMISSION_GRANTED){
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission_group.STORAGE)) {
//                // show an explanation why you need this permission
//                Snackbar snackbar = Snackbar
//                        .make(this.findViewById(android.R.id.content), "Please grant Storage permission for this app from settings.", Snackbar.LENGTH_LONG);
//                snackbar.show();
//            } else {
//                // No explanation needed
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission_group.STORAGE}, MY_PERMISSION_REQUEST_STORAGE);
//                // MY_PERMISSION_REQUEST_CAMERA is an app defined constant
//            }
//        }
//        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//                // show an explanation why you need this permission
//                Snackbar snackbar = Snackbar
//                        .make(this.findViewById(android.R.id.content), "Please grant this permission to this app for accessing treasure hunt photos.", Snackbar.LENGTH_LONG);
//                snackbar.show();
//            } else {
//                // No explanation needed
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_READ_STORAGE);
//                // MY_PERMISSION_REQUEST_CAMERA is an app defined constant
//            }
//        }
//        if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                // show an explanation why you need this permission
//                Snackbar snackbar = Snackbar
//                        .make(this.findViewById(android.R.id.content), "Please grant this permission to this app for saving treasure hunt photos.", Snackbar.LENGTH_LONG);
//                snackbar.show();
//            } else {
//                // No explanation needed
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_WRITE_STORAGE);
//                // MY_PERMISSION_REQUEST_CAMERA is an app defined constant
//            }
//        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                // show an explanation why you need this permission
                Snackbar snackbar = Snackbar
                        .make(this.findViewById(android.R.id.content), "Please grant Camera permission for this app from settings.", Snackbar.LENGTH_LONG);
                snackbar.show();
            } else {
                // No explanation needed
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSION_REQUEST_CAMERA);
            }
        }  else{
            // Permission has already been granted.
            for(int i = 0; i < 4; i++){
                buttonArrayList.get(i).setEnabled(true);
                final int finalI = i;
                buttonArrayList.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), CameraActivity.class);
                        startActivityForResult(intent, finalI);
                    }
                });
            }
        }
        refreshQuestions();

//        final ArrayList<ImageView> expand = new ArrayList<>();
//        for(int i = 0; i < 4; i++){
//            expand.add((ImageView) cards.get(i).findViewById(R.id.iv_expand));
//            final int finalI = i;
//            expand.get(i).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if(!isExpanded.get(finalI)){
//                        Picasso.with(getBaseContext()).load(R.drawable.informalslogo).fit().centerCrop().into(imageViews.get(finalI));
//                        imageViews.get(finalI).setVisibility(View.VISIBLE);
//                        expand.get(finalI).setImageResource(R.drawable.ic_expand_less_black_24dp);
//                        expand.get(finalI).setColorFilter(getBaseContext().getResources().getColor(R.color.white));
//                        isExpanded.set(finalI, true);
//                    }   else {
//                        imageViews.get(finalI).setVisibility(View.GONE);
//                        expand.get(finalI).setImageResource(R.drawable.ic_expand_more_black_24dp);
//                        expand.get(finalI).setColorFilter(getBaseContext().getResources().getColor(R.color.white));
//                        isExpanded.set(finalI, false);
//                    }
//                }
//            });
//        }
    }

    private void setSkipVisible() {
        for(int i = 0; i < 4; i++){
            skipArrayList.get(i).setVisibility(View.VISIBLE);
        }
    }

    private void setSkipInvisible() {
        for(int i = 0; i < 4; i++){
            skipArrayList.get(i).setVisibility(View.GONE);
        }
    }

    private void setSkipped(final int questionId) {
        //Toast.makeText(getApplicationContext(), "Skipping", Toast.LENGTH_SHORT).show();
        String url = getResources().getString(R.string.url_base) +"treasurehunt/skip.php";
        //int return_val;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    LogUtils.debug("SKIP",response);
                    returned_status = jsonObject.getInt("status");
                    switch (returned_status){
                        case 0 :
                            Toast.makeText(getBaseContext(), "Marked As Skipped", Toast.LENGTH_SHORT).show();
                            refreshQuestions();
                            break;
                        case 128 :
                            new AlertDialog.Builder(QuestionsActivity.this)
                                    .setMessage("Solve all other clues to Skip.")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .show();
                            break;
                        case 8 :
                            new AlertDialog.Builder(QuestionsActivity.this)
                                    .setMessage("The event has ended.")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(QuestionsActivity.this, AnswersActivity.class);
                                            startActivity(intent);
                                        }
                                    })
                                    .show();
                            break;
                        case 64 :
                            new AlertDialog.Builder(QuestionsActivity.this)
                                    .setMessage("Cannot Skip these clues.")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .show();
                            break;
                        case 32 :
                            new AlertDialog.Builder(QuestionsActivity.this)
                                    .setMessage("Answered clues cannot be skipped.")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            refreshQuestions();
                                        }
                                    })
                                    .show();
                            break;
                        default :
                            LogUtils.info("ERROR", " " + returned_status);
                            Toast.makeText(getBaseContext(), "Server error. Please try again.", Toast.LENGTH_SHORT).show();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtils.info("Error","Unable to fetch");
                Toast.makeText(getBaseContext(), "Network error. Please try again.", Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("ID",String.valueOf(questionId));
                String name = Utils.getprefString(UtilStrings.NAME,getBaseContext());
                params.put("SUBMITTED_BY",name);
                name = name.substring(0, name.indexOf('_'));
                params.put("TEAM_NAME",name);
                LogUtils.info("SKIP_PARAMS", name+" "+String.valueOf(questionId));
                return params;
            }
        };

        MySingleton.getInstance(getBaseContext()).addToRequestQueue(request);
    }

    private int getCountForBatch(int batch) {
        switch(batch) {
            case 3:
                return 3;
            case 4:
                return 2;
            case 5:
                return 1;
            case 1:
            case 2:
            default:
                return 4;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
        switch(requestCode){
            case MY_PERMISSION_REQUEST_CAMERA:{
                // if request is cancelled then grantResults array will be empty
                LogUtils.info("PERMISSION", "ITS HERE");
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    // permission granted
                    LogUtils.info("PERMISSION", "ITS HERE enabled");

                    for(int i = 0; i < cardCount; i++) {
                        buttonArrayList.get(i).setEnabled(true);
                        final int finalI = i;
                        buttonArrayList.get(i).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(getApplicationContext(), CameraActivity.class);
                                startActivityForResult(intent, finalI);
                            }
                        });
                    }
                } else{
                    // permission denied
                    LogUtils.info("PERMISSION", "ITS HERE disabled");

                    for(int i = 0; i < cardCount; i++)
                        buttonArrayList.get(i).setEnabled(false);
                }
            }   break;
            case MY_PERMISSION_REQUEST_READ_STORAGE:
                break;
            case MY_PERMISSION_REQUEST_WRITE_STORAGE:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) return;
        else{
            String filename = data.getStringExtra(CameraFragment.EXTRA_PHOTO_FILENAME);
            boolean backcamera = data.getBooleanExtra("backcamera", true);
            if(filename != null){
                clueArrayList.get(requestCode).setAnswerImageFilename(filename);
                clueArrayList.get(requestCode).setBackcamera(backcamera);
                callSetSolvedAPI(clueIds.get(requestCode), requestCode);
            }
        }
    }

    private void refreshQuestions(){
        //add code for refreshing questions here
        String url = getResources().getString(R.string.url_base) +"treasurehunt/getCluesFinal.php";
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    LogUtils.debug("ClueResponse", response);
                    LogUtils.debug("TEAM_NAME",Utils.getprefString(UtilStrings.NAME,getBaseContext()).substring(0,UtilStrings.NAME.length()-4));
                    int status = jsonObject.getInt("status");
                    switch(status){
                        case 0:
                            batch = jsonObject.getInt("batch");
                            cardCount = getCountForBatch(batch);
                            if(batch > 3)  setSkipInvisible();
                            else    setSkipVisible();
                            Utils.saveprefInt(UtilStrings.BATCH_NUM, batch,QuestionsActivity.this);
                            JSONArray jsonArray = jsonObject.getJSONArray("clues");
                            cardCount = jsonArray.length();
                            for(int i = 0; i < 4; i++){
                                cards.get(i).setVisibility(View.GONE);
                                cards.get(i).findViewById(R.id.status_qn).setBackgroundColor(getResources().getColor(R.color.white));
                            }
                            clues = new ArrayList<>();
                            clueIds = new ArrayList<>();
                            clueArrayList = new ArrayList<>();

                            for(int i = 0; i < cardCount; i++){
                                cards.get(i).setVisibility(View.VISIBLE);
                                clues.add(jsonArray.getJSONObject(i).getString("questions"));
                                clueIds.add(jsonArray.getJSONObject(i).getInt("id"));
                                clueArrayList.add(new Clue());
                                if(isURL(clues.get(i))){
                                    clueArrayList.get(i).setQuestionImageUrl(clues.get(i));
                                    Picasso.with(getBaseContext()).setLoggingEnabled(true);
                                    imageViews.get(i).setVisibility(View.VISIBLE);
                                    Picasso.with(getBaseContext()).load(clues.get(i)).into(imageViews.get(i));
                                    textViews.get(i).setVisibility(View.GONE);
                                    clueArrayList.get(i).setQuestionImageUrl(clues.get(i));
                                }
                                else {
                                    clueArrayList.get(i).setQuestionText(clues.get(i));
                                    imageViews.get(i).setVisibility(View.GONE);
                                    textViews.get(i).setVisibility(View.VISIBLE);
                                    textViews.get(i).setText(clues.get(i));
                                    clueArrayList.get(i).setQuestionText(clues.get(i));
                                }
                                clueArrayList.get(i).setQuestionID(clueIds.get(i));
                                int solved = jsonArray.getJSONObject(i).getInt("solved");
                                switch(solved){
                                    case 0 :
                                        buttonArrayList.get(i).setVisibility(View.VISIBLE);
                                        skipArrayList.get(i).setVisibility(View.VISIBLE);
                                        break;
                                    case 1 :
                                        buttonArrayList.get(i).setVisibility(View.GONE);
                                        skipArrayList.get(i).setVisibility(View.GONE);
                                        cards.get(i).findViewById(R.id.status_qn).setBackgroundColor(getResources().getColor(R.color.colorLightGreen));
                                        break;
                                    case 2 :
                                        buttonArrayList.get(i).setVisibility(View.GONE);
                                        skipArrayList.get(i).setVisibility(View.GONE);
                                        cards.get(i).findViewById(R.id.status_qn).setBackgroundColor(getResources().getColor(R.color.red));
                                        break;
                                }
                            }

                            progressDialog.dismiss();
                            break;
                        case 1:
                            progressDialog.dismiss();
                            new AlertDialog.Builder(QuestionsActivity.this)
                                 .setMessage("You have completed the treasure hunt.")
                                 .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface dialog, int which) {
                                         dialog.dismiss();
                                     }
                                 })
                                 .show();
                            break;
                        case 4:
                            progressDialog.dismiss();
                            progressDialog.dismiss();
                            new AlertDialog.Builder(QuestionsActivity.this)
                                 .setMessage("The event has ended.")
                                 .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface dialog, int which) {
                                         dialog.dismiss();
                                     }
                                 })
                                 .show();
                            break;
                        default:
                            progressDialog.dismiss();
                            LogUtils.info("ERROR REFRESH", " "+status );
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //LogUtils.info("Error","Unable to fetch");
                progressDialog.dismiss();
                Toast.makeText(getBaseContext(), "Network error!", Toast.LENGTH_SHORT).show();
                refreshQuestions();

            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                String name = Utils.getprefString(UtilStrings.NAME,getBaseContext());
                name = name.substring(0, name.indexOf('_'));
                params.put("TEAM_NAME",name);
                LogUtils.info("MY TEAM", name);
                return params;
            }
        };

        MySingleton.getInstance(getBaseContext()).addToRequestQueue(request);
        progressDialog = new ProgressDialog(QuestionsActivity.this);
        progressDialog.setMessage("Loading");
        progressDialog.show();
    }

    private void callSetSolvedAPI(final int id,final int requestCode){
        String url = getResources().getString(R.string.url_base) +"treasurehunt/setSolvedFinal.php";
        //int return_val;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    LogUtils.debug("SolvedResponse",response);
                    returned_status = jsonObject.getInt("status");
                    switch (returned_status){
                        case 0 :
                            Toast.makeText(getBaseContext(), "Already solved by teammate.", Toast.LENGTH_SHORT).show();
                            break;
                        case 1 :
                            clueArrayList.get(requestCode).setSolved(true);
                            Toast.makeText(getBaseContext(), "Successfully Updated", Toast.LENGTH_SHORT).show();
                            ClueList.getInstance(getApplicationContext()).addClue(clueArrayList.get(requestCode));
                            break;
                        case 4 :
                            new AlertDialog.Builder(QuestionsActivity.this)
                                    .setMessage("The event has ended.")
                                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(QuestionsActivity.this, AnswersActivity.class);
                                            startActivity(intent);
                                        }
                                    })
                                    .show();
                            break;
                        default :
                            LogUtils.info("ERROR", " " + returned_status);
                    }
                    refreshQuestions();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //LogUtils.info("Error","Unable to fetch");
                //Internet

            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
//                params.put("TEAM_NAME",Utils.getprefString(UtilStrings.NAME,getBaseContext()).substring(0,UtilStrings.NAME.length()-4));
                params.put("ID",String.valueOf(id));
                String name = Utils.getprefString(UtilStrings.NAME,getBaseContext());
                params.put("SUBMITTED_BY",name);
                name = name.substring(0, name.indexOf('_'));
                params.put("TEAM_NAME",name);
                return params;
            }
        };

        MySingleton.getInstance(getBaseContext()).addToRequestQueue(request);
    }

    private boolean isURL(String s){
        try {
            new URL(s).toURI();
            return true;
        }

        // If there was an Exception
        // while creating URL object
        catch (Exception e) {
            return false;
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            Intent intent = new Intent(QuestionsActivity.this, HomeActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, 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_about) {
            Intent intent = new Intent(QuestionsActivity.this, AboutUsActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_log_out) {
            LogOutAlertClass lg = new LogOutAlertClass();
            lg.isSure(QuestionsActivity.this);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onPause(){
        super.onPause();
        ClueList.getInstance(getApplicationContext()).saveClues();
    }
}
