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.content.SharedPreferences;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
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.util.Log;
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 android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.b2lmobitech.spottest.adapter.ItemSelectedListener;
import com.b2lmobitech.spottest.adapter.SectionAdapter;
import com.b2lmobitech.spottest.adapter.SectionAdapterlocal;
import com.b2lmobitech.spottest.encaps.Section;
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.io.File;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class SectionsActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    ImageView snapshot,timerIcon;
    private GestureOverlayView gestureOverlayView;
    private NestedScrollView nestedScrollView;
    TextView alertText;

    String groupId;
    String assignId;
    JSONArray sectionsArray;
    private TextView timerText;
    File mediaFile;
    private static final int CAPTURE_NUMBER=2,REQUEST_CHECK_SETTINGS=1;
    Uri imageUri;
    String camString="",signString="",storedassignid="";
    Handler handler = new Handler();
    int alert1=-1,alert2=-1;
    MyRequestQueue myRequestQueue;
    boolean showResult=true;
    boolean isSubmiting=false;
    private MenuItem doneitem,refreshitem;
    private Context mycontext;
    private boolean refreshstate ;
    private RequestQueue mRequestQueue;
    ArrayList<Section> sectionArraylocal=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sections);
        SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("lastActivity", getClass().getName());
        editor.apply();
        //--swathi--//
        refreshstate = true;
        invalidateOptionsMenu();
        storedassignid = prefs.getString("assignid","");
        //--swathi--//
        Toolbar toolbar =  findViewById(R.id.toolbar);
        Button submit_buttonsection =  findViewById(R.id.submit_buttonsection);
mycontext = this;
        setSupportActionBar(toolbar);
         if(getIntent().getStringExtra("assignid")!=null)
         {
             assignId =getIntent().getStringExtra("assignid");
            // Toast.makeText(this,"not null,assignId = "+assignId,Toast.LENGTH_SHORT).show();
         }
        else
        {
            assignId = storedassignid;
            //Toast.makeText(this,"null,assignId = "+assignId,Toast.LENGTH_SHORT).show();
        }
//        Toast.makeText(this,"assignId = "+assignId,Toast.LENGTH_SHORT).show();
        timerText=findViewById(R.id.timerText);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        //--swathi--//
        DataBase dataBase = new DataBase(this);
        dataBase.deletesectiontable();
        //--swathi--//
        getWidgets();
        if(!isNetworkAvailable()) {
            Toast.makeText(this,"please check internet connection ",Toast.LENGTH_SHORT).show();
        }
            //Toast.makeText(this,"getSections()",Toast.LENGTH_SHORT).show();
            getSections(true);
            startService();

        submit_buttonsection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mycontext);

// Add the buttons
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked OK button
                        dialog.dismiss();
                        MySnackbar.getInstance(SectionsActivity.this).dismiss();
                        //invalidateOptionsMenu();
                        doneitem.setEnabled(false);
                        doneitem.getIcon().setAlpha(130);
                        submitAnswer();
                    }
                });

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

                builder.setMessage("Do you want to really submit?");

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

    }

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

    int starttime=0;

    private void getSections(final boolean goNext) {
        myRequestQueue = MyRequestQueue.getInstance(this);
    myRequestQueue.showProgressBar();
//---swathi--
        StringRequest postRequest = new StringRequest(Request.Method.POST,URL.GET_SECTIONS,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                        if (response != null && response.length() > 0) {
                            if (goNext) {
                                if (!isNetworkAvailable()) {
                                    Toast.makeText(SectionsActivity.this, "please check internet connection and click refresh button", Toast.LENGTH_SHORT).show();
                                    refreshstate = true;
                                    invalidateOptionsMenu();
                                } else {
//                            Toast.makeText(SectionsActivity.this,"gonext",Toast.LENGTH_SHORT).show();
                                    getQuestions();
                                }
                            } else {
                                myRequestQueue.hideProgressBar();
                            }

                            try {

//                        Toast.makeText(SectionsActivity.this,"set sections",Toast.LENGTH_SHORT).show();
                                    setSections(new JSONObject(response));

                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
                                refreshstate = true;
                                invalidateOptionsMenu();
                            }
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        myRequestQueue.hideProgressBar();
                        Log.d("Error.Response", error.toString());
                        //--swathi--

                        //--swathi--
                        // Toast.makeText(activity, "Myrequestqueue="+error.toString(),Toast.LENGTH_LONG).show();
                        //myRequestFinishedListener.requestResult(error.toString());
                        //--swathi
                        DataBase dataBase=new DataBase(SectionsActivity.this);
                        String message = null;
                        if (error instanceof NetworkError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            if(dataBase.getSections().size()!=0)
                            {
                                setsectionssub();
                            }
                            else {
                                alertdiaolg("Please check internet connection");
                            }
                        } else if (error instanceof ServerError) {
                            message = "The server could not be found. Please try again after some time!!";

                                refreshstate = true;
                                invalidateOptionsMenu();

                        } else if (error instanceof AuthFailureError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            if(dataBase.getSections().size()!=0)
                            {
                                setsectionssub();
                            }
                            else {
                                refreshstate = true;
                                invalidateOptionsMenu();
                            }
                        } else if (error instanceof ParseError) {
                            message = "Parsing error! Please try again after some time!!";

                                refreshstate = true;
                                invalidateOptionsMenu();

                        } else if (error instanceof NoConnectionError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            if(dataBase.getSections().size()!=0)
                            {
                                setsectionssub();
                            }
                            else {
                                alertdiaolg("Please check internet connection");
                            }
                        } else if (error instanceof TimeoutError) {
                            message = "Connection TimeOut! Please check your internet connection.";

                                refreshstate = true;
                                invalidateOptionsMenu();

                        }
//                        myRequestFinishedListener.requestResult(message);
//                        //--swathi
//                        Log.d("message", message);


                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<>();
                //  Toast.makeText(this,"assignId = "+assignId+"\n, email = "+Preference.getInstance(this).getStudentId(),Toast.LENGTH_SHORT).show();
                params.put("email", Preference.getInstance(SectionsActivity.this).getStudentId());
                params.put("assignId", assignId);

                return params;
            }
        };

        postRequest.setRetryPolicy(new DefaultRetryPolicy(240 * 1000, 1, 1.0f));

        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        mRequestQueue.add(postRequest);

        //--swathi--
//    Map<String, String> params = new HashMap<>();
//    //  Toast.makeText(this,"assignId = "+assignId+"\n, email = "+Preference.getInstance(this).getStudentId(),Toast.LENGTH_SHORT).show();
//    params.put("email", Preference.getInstance(this).getStudentId());
//    params.put("assignId", assignId);
//
//    myRequestQueue = MyRequestQueue.getInstance(this);
//    myRequestQueue.showProgressBar();
//    myRequestQueue.addToQueueWithoutProgress(URL.GET_SECTIONS, params, new MyRequestQueue.MyRequestFinishedListener() {
//        @Override
//        public void requestResult(String response) {
////                Toast.makeText(mycontext,"response"+response.toString(),Toast.LENGTH_SHORT).show();
////            Toast.makeText(mycontext,"response.length()="+response.length(),Toast.LENGTH_SHORT).show();
//            if (response != null && response.length() > 0) {
//                if (goNext) {
//                    if (!isNetworkAvailable()) {
//                        Toast.makeText(SectionsActivity.this, "please check internet connection and click refresh button", Toast.LENGTH_SHORT).show();
//                        refreshstate = true;
//                        invalidateOptionsMenu();
//                    } else {
////                            Toast.makeText(SectionsActivity.this,"gonext",Toast.LENGTH_SHORT).show();
//                        getQuestions();
//                    }
//                } else {
//                    myRequestQueue.hideProgressBar();
//                }
//
//                try {
//                    if(response.toString().equalsIgnoreCase("Cannot connect to Internet...Please check your connection!"))
//                    {
//                        alertdiaolg("Please check internet connection");
//                    }
//                    else {
////                        Toast.makeText(SectionsActivity.this,"set sections",Toast.LENGTH_SHORT).show();
//                        setSections(new JSONObject(response));
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                    Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
//                    refreshstate = true;
//                    invalidateOptionsMenu();
//                }
//            }
////            else
////            {
////                Toast.makeText(SectionsActivity.this, "else part", Toast.LENGTH_LONG).show();
////            }
//
//
//        }
//    });

    }

    private void getQuestions() {
//        Toast.makeText(this,"getQuestions()",Toast.LENGTH_SHORT).show();
        final DataBase dataBase=new DataBase(this);
        //---swathi--
        myRequestQueue = MyRequestQueue.getInstance(this);
        myRequestQueue.showProgressBar();
        StringRequest postRequest = new StringRequest(Request.Method.POST,URL.GET_QUESTIONS,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);

                        try {
                            if (response != null && response.length() > 0) {
                                if(!isNetworkAvailable()) {
                                    Toast.makeText(SectionsActivity.this,"please check internet connection and click refresh button",Toast.LENGTH_SHORT).show();
                                    refreshstate = true;
                                    invalidateOptionsMenu();
                                }
                                else {
                                    getOptions();
                                }
                                JSONObject questionobject = new JSONObject(response);

                                if (questionobject != null) {
                                    int questioncheck = questionobject.getInt("s");

////                    Toast.makeText(SectionsActivity.this,"getQuestions()="+questionsArray.length(),Toast.LENGTH_SHORT).show();
//                    Toast.makeText(SectionsActivity.this,"questioncheck="+questioncheck,Toast.LENGTH_SHORT).show();
                                    if (questioncheck != 1) {
//                                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded", Toast.LENGTH_SHORT).show();
//                                refreshstate = true;
//                                invalidateOptionsMenu();
                                    } else {//1
                                        JSONArray questionsArray = new JSONObject(response).getJSONArray("questions");
                                        if (questionsArray != null) {
                                            for (int i = 0; i < questionsArray.length(); i++) {
                                                dataBase.insertQuestion(questionsArray.getJSONObject(i));
                                            }
                                        }

                                    }
                                    refreshstate = false;
                                    invalidateOptionsMenu();
                                }
//                        else
//                        {
//                            Toast.makeText(SectionsActivity.this, "question object null", Toast.LENGTH_SHORT).show();
//                        }
                            }
                            else
                            {
                                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
                                refreshstate = true;
                                invalidateOptionsMenu();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            //  Toast.makeText(SectionsActivity.this,"error1="+e.toString(),Toast.LENGTH_SHORT).show();
                            Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
                            refreshstate = true;
                            invalidateOptionsMenu();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        myRequestQueue.hideProgressBar();
                        Log.d("Error.Response", error.toString());
                        //--swathi--

                        //--swathi--
                        // Toast.makeText(activity, "Myrequestqueue="+error.toString(),Toast.LENGTH_LONG).show();
                        //myRequestFinishedListener.requestResult(error.toString());
                        //--swathi
                        String message = null;
                        if (error instanceof NetworkError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            alertdiaolg("Please check internet connection");
                        } else if (error instanceof ServerError) {
                            message = "The server could not be found. Please try again after some time!!";
                            refreshstate = true;
                            invalidateOptionsMenu();
                        } else if (error instanceof AuthFailureError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            refreshstate = true;
                            invalidateOptionsMenu();
                        } else if (error instanceof ParseError) {
                            message = "Parsing error! Please try again after some time!!";
                            refreshstate = true;
                            invalidateOptionsMenu();
                        } else if (error instanceof NoConnectionError) {
                            message = "Cannot connect to Internet...Please check your connection!";
                            alertdiaolg("Please check internet connection");
                        } else if (error instanceof TimeoutError) {
                            message = "Connection TimeOut! Please check your internet connection.";
                            refreshstate = true;
                            invalidateOptionsMenu();
                        }
//                        myRequestFinishedListener.requestResult(message);
//                        //--swathi
//                        Log.d("message", message);
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<>();
                params.put("email", Preference.getInstance(SectionsActivity.this).getStudentId());
                params.put("assignId", assignId);

                return params;
            }
        };

        postRequest.setRetryPolicy(new DefaultRetryPolicy(240 * 1000, 1, 1.0f));

        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        mRequestQueue.add(postRequest);

        //--swathi--

//        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) {
////                Toast.makeText(mycontext,"In get_questions",Toast.LENGTH_SHORT).show();
//                if(!isNetworkAvailable()) {
//                    Toast.makeText(SectionsActivity.this,"please check internet connection and click refresh button",Toast.LENGTH_SHORT).show();
//                    refreshstate = true;
//                    invalidateOptionsMenu();
//                }
//                else {
//                    getOptions();
//                }
//                try {
//                    if (response != null && response.length() > 0) {
//                        JSONObject questionobject = new JSONObject(response);
//
//                        if (questionobject != null) {
//                            int questioncheck = questionobject.getInt("s");
//
//////                    Toast.makeText(SectionsActivity.this,"getQuestions()="+questionsArray.length(),Toast.LENGTH_SHORT).show();
////                    Toast.makeText(SectionsActivity.this,"questioncheck="+questioncheck,Toast.LENGTH_SHORT).show();
//                            if (questioncheck != 1) {
////                                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded", Toast.LENGTH_SHORT).show();
////                                refreshstate = true;
////                                invalidateOptionsMenu();
//                            } else {//1
//                                JSONArray questionsArray = new JSONObject(response).getJSONArray("questions");
//                                if (questionsArray != null) {
//                                    for (int i = 0; i < questionsArray.length(); i++) {
//                                        dataBase.insertQuestion(questionsArray.getJSONObject(i));
//                                    }
//                                }
//
//                        }
//                            refreshstate = false;
//                            invalidateOptionsMenu();
//                        }
////                        else
////                        {
////                            Toast.makeText(SectionsActivity.this, "question object null", Toast.LENGTH_SHORT).show();
////                        }
//                    }
//                    else
//                    {
//                        Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
//                        refreshstate = true;
//                        invalidateOptionsMenu();
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                  //  Toast.makeText(SectionsActivity.this,"error1="+e.toString(),Toast.LENGTH_SHORT).show();
//                    Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
//                    refreshstate = true;
//                    invalidateOptionsMenu();
//                }
//            }
//        });
    }

    private void getOptions() {
        final DataBase dataBase=new DataBase(this);

        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) {
                //Toast.makeText(mycontext,"In get_options",Toast.LENGTH_SHORT).show();
                try {
                myRequestQueue.hideProgressBar();

                    if (response != null && response.length() > 0) {
                   // Toast.makeText(SectionsActivity.this,"response.length() ="+response.length(),Toast.LENGTH_SHORT).show();
                    JSONObject optionobject = new JSONObject(response);

                        if(optionobject!=null) {
                            int optioncheck =  optionobject.getInt("s");
//                    Toast.makeText(SectionsActivity.this,"getQuestions()="+questionsArray.length(),Toast.LENGTH_SHORT).show();
//                            Toast.makeText(SectionsActivity.this, "optioncheck=" + optioncheck, Toast.LENGTH_LONG).show();
                            if (optioncheck != 1) {
//                                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded", Toast.LENGTH_LONG).show();
//                                refreshstate = true;
//                                invalidateOptionsMenu();
                            } else {
                                JSONArray optionsArray = new JSONObject(response).getJSONArray("options");
                                if (optionsArray != null) {
                                    for (int i = 0; i < optionsArray.length(); i++) {
                                        dataBase.insertOptions(optionsArray.getJSONObject(i), assignId);
                                    }
                                }

                            }
                            refreshstate = false;
                            invalidateOptionsMenu();
                        }
//                        else
//                        {
//                            Toast.makeText(SectionsActivity.this, "option object null", Toast.LENGTH_LONG).show();
//                        }
                    }
                    else
                    {
                        Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
                        refreshstate = true;
                        invalidateOptionsMenu();
                    }
//
                } catch (JSONException e) {
                    e.printStackTrace();
                  //  Toast.makeText(SectionsActivity.this,"error2="+e.toString(),Toast.LENGTH_LONG).show();
                    Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
                    refreshstate = true;
                    invalidateOptionsMenu();
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        Toast.makeText(this,"onrestart",Toast.LENGTH_SHORT).show();

        if(!isNetworkAvailable()) {
            Toast.makeText(this,"please check internet connection",Toast.LENGTH_SHORT).show();
            refreshstate = true;
            invalidateOptionsMenu();
        }
        else
        {
            refreshstate = false;
            invalidateOptionsMenu();
        }
        if(assignId==null)
        {
            assignId = storedassignid;
           // Toast.makeText(this,"null,assignId = "+assignId,Toast.LENGTH_SHORT).show();
        }
        getSections(false);
    }

    private void setSections(final JSONObject jsonObject) throws JSONException {
//        Toast.makeText(SectionsActivity.this,"setSections",Toast.LENGTH_SHORT).show();


        if(jsonObject!=null) {
            int sectioncheck = jsonObject.getInt("s");
//                    Toast.makeText(SectionsActivity.this,"getQuestions()="+questionsArray.length(),Toast.LENGTH_SHORT).show();
//                            Toast.makeText(SectionsActivity.this, "optioncheck=" + optioncheck, Toast.LENGTH_LONG).show();
            if (sectioncheck == 2) {
                Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded", Toast.LENGTH_LONG).show();
                refreshstate = true;
                invalidateOptionsMenu();
            }
            else {
                refreshstate = false;
                invalidateOptionsMenu();

        sectionsArray=jsonObject.getJSONArray("sections");
        if(sectionsArray!=null) {
//        Toast.makeText(SectionsActivity.this,"sectionsArray.length() ="+sectionsArray.length(),Toast.LENGTH_SHORT).show();
            JSONObject dataObject = jsonObject.getJSONObject("test");

//            final int diff = jsonObject.getInt("diff");
////        Toast.makeText(SectionsActivity.this,"diff ="+diff,Toast.LENGTH_SHORT).show();
//
//            if (diff > 0) {
//                handler.removeCallbacksAndMessages(null);
//                startTimer(diff);
//                alertText.setVisibility(View.GONE);
//            } else {
//                timerText.setVisibility(View.GONE);
//                timerIcon.setVisibility(View.GONE);
//                alertText.setVisibility(View.VISIBLE);
//                alertSubmit();
//            }
//
//            if (jsonObject.getString("showResult").equals("yes")) {
//                showResult = true;
//            } else {
//                showResult = false;
//            }
//
//
//            alert1 = jsonObject.getInt("alert1");
//            alert2 = jsonObject.getInt("alert2");
            //--swathi--//I placed here also,bcoz in few papers,once questions submitted,it may or may not go to resultactivity according to logic
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("diff",jsonObject.getInt("diff"));
            editor.putString("showResult",jsonObject.getString("showResult"));
            editor.putInt("alert1",jsonObject.getInt("alert1"));
            editor.putInt("alert2",jsonObject.getInt("alert2"));
            editor.putString("examseconds",jsonObject.getString("examseconds"));
//            Toast.makeText(SectionsActivity.this,"examseconds_insub1="+"hai",Toast.LENGTH_LONG).show();
//            Toast.makeText(SectionsActivity.this,"examseconds_insub="+jsonObject.getInt("examseconds"),Toast.LENGTH_LONG).show();
            editor.apply();
//        Toast.makeText(getApplicationContext(), "2="+prefs.getString("lastActivity", SplashActivity.class.getName()),Toast.LENGTH_SHORT).show();
            //--swathi--//

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

            DataBase dataBase = new DataBase(this);
            dataBase.deletesectiontable();
            for (int i = 0; i < sectionsArray.length(); i++) {
                dataBase.insertsection(sectionsArray.getJSONObject(i),sectionsArray.getJSONObject(i).getInt("counts"),dataBase.getAnswers( sectionsArray.getJSONObject(i).getString("section_id")
                        , assignId).size());
//                sectionArraylocal.get(i).setanswered(dataBase.getAnswers( sectionsArray.getJSONObject(i).getString("section_id")
//                        , assignId).size());
//                sectionArraylocal.get(i).setcounts( sectionsArray.getJSONObject(i).getInt("counts"));
            }
            setsectionssub();
//            sectionArraylocal=dataBase.getSections();
////            for (int i = 0; i < sectionsArray.length(); i++) {
////
////                sectionArraylocal.get(i).setanswered();
////                sectionArraylocal.get(i).setcounts( );
////            }
//
////           for (int i = 0; i < sectionsArray.length(); i++) {
//////            Toast.makeText(SectionsActivity.this,"i ="+i,Toast.LENGTH_SHORT).show();
//////            Toast.makeText(SectionsActivity.this,"dataBase ="+dataBase.getAnswers(
//////                    sectionsArray.getJSONObject(i).getString("section_id"),assignId).size(),Toast.LENGTH_SHORT).show();
////                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("expired", diff < 0);
////                              startActivity(intent);
////                          } catch (JSONException e) {
////                             // e.printStackTrace();
//////                              Toast.makeText(getApplicationContext(),"e1="+e.toString(),Toast.LENGTH_LONG).show();
////                          }
////                      }
////                  }, diff > 0);
//
//            SectionAdapterlocal sectionAdapter = new SectionAdapterlocal(
//                    getApplicationContext(), sectionArraylocal, new ItemSelectedListener() {
//                @Override
//                public void selected(int position) {
////                    try {
//                        Intent intent = new Intent(getApplicationContext(), QuestionsActivity.class);
//                        intent.putExtra("preview", sectionArraylocal.get(position).getanswered() != 0);
//                        intent.putExtra("section", sectionArraylocal.get(position).getsectionId());
//                        intent.putExtra("assignId", assignId);
//                        intent.putExtra("expired", diff < 0);
//                        startActivity(intent);
////                    } catch (JSONException e) {
////                        // e.printStackTrace();
//////                              Toast.makeText(getApplicationContext(),"e1="+e.toString(),Toast.LENGTH_LONG).show();
////                    }
//                }
//            }, diff > 0);
//
//            recyclerView.setAdapter(sectionAdapter);
//
//            nestedScrollView.setVisibility(View.VISIBLE);
        }
//        else
//        {
//            Toast.makeText(SectionsActivity.this, "section array null", Toast.LENGTH_SHORT).show();
//        }

            }
        }
        else
        {
            Toast.makeText(SectionsActivity.this, "It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
            refreshstate = true;
            invalidateOptionsMenu();
        }
    }
private void setsectionssub()
{
//    Toast.makeText(SectionsActivity.this,"setsectionssub",Toast.LENGTH_LONG).show();
    final int diff_stored,alert1_stored,alert2_stored;
    final String examseconds_stored;
    long currenttimeInseconds;
    Date date;
    SimpleDateFormat dateFormat;
    String showResult_stored;
    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    DataBase dataBase = new DataBase(this);
    sectionArraylocal=dataBase.getSections();
    diff_stored = prefs.getInt("diff",0);
    examseconds_stored = prefs.getString("examseconds","");
    showResult_stored = prefs.getString("showResult","");
    alert1_stored = prefs.getInt("alert1",0);
    alert2_stored = prefs.getInt("alert2",0);
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    date = new Date();
    currenttimeInseconds = date.getTime()/(1000);
    try {
        Date examtotaldate = dateFormat.parse(examseconds_stored);
        Toast.makeText(SectionsActivity.this,"examtotaldatesec="+(examtotaldate.getTime()/(1000)),Toast.LENGTH_LONG).show();
    }catch(ParseException e)
    {

    }
    Toast.makeText(SectionsActivity.this,"diff_local="+(currenttimeInseconds - examseconds_stored),Toast.LENGTH_LONG).show();
//    Toast.makeText(SectionsActivity.this,"diff_local="+(timeInMilliseconds - examseconds_stored),Toast.LENGTH_LONG).show();
//    Toast.makeText(SectionsActivity.this,"examseconds_stored="+examseconds_stored,Toast.LENGTH_LONG).show();
    Toast.makeText(SectionsActivity.this,"diff_server="+diff_stored,Toast.LENGTH_LONG).show();
    if (diff_stored > 0) {
        handler.removeCallbacksAndMessages(null);
        startTimer(diff_stored);
        alertText.setVisibility(View.GONE);
    } else {
        timerText.setVisibility(View.GONE);
        timerIcon.setVisibility(View.GONE);
        alertText.setVisibility(View.VISIBLE);
        alertSubmit();
    }

    if (showResult_stored.equals("yes")) {
        showResult = true;
    } else {
        showResult = false;
    }


    alert1 = alert1_stored;
    alert2 = alert2_stored;

    for (int i = 0; i < sectionArraylocal.size(); i++) {

        dataBase.Updatesectionanswer(sectionArraylocal.get(i).getsectionId(),dataBase.getAnswers(sectionArraylocal.get(i).getsectionId()
                , assignId).size());

    }
    sectionArraylocal = new ArrayList<>();
    sectionArraylocal=dataBase.getSections();
//    Toast.makeText(SectionsActivity.this,"answered="+dataBase.getAnswers(sectionArraylocal.get(0).getsectionId()
//            , assignId).size(),Toast.LENGTH_LONG).show();
//    Toast.makeText(SectionsActivity.this,"b_answered="+sectionArraylocal.get(0).getanswered(),Toast.LENGTH_LONG).show();
    SectionAdapterlocal sectionAdapter = new SectionAdapterlocal(
            getApplicationContext(), sectionArraylocal, new ItemSelectedListener() {
        @Override
        public void selected(int position) {
//                    try {
            Intent intent = new Intent(getApplicationContext(), QuestionsActivity.class);
            intent.putExtra("preview", sectionArraylocal.get(position).getanswered() != 0);
            intent.putExtra("section", sectionArraylocal.get(position).getsectionId());
            intent.putExtra("assignId", assignId);
            intent.putExtra("expired", diff_stored < 0);
            startActivity(intent);
//                    } catch (JSONException e) {
//                        // e.printStackTrace();
////                              Toast.makeText(getApplicationContext(),"e1="+e.toString(),Toast.LENGTH_LONG).show();
//                    }
        }
    }, diff_stored > 0);

    recyclerView.setAdapter(sectionAdapter);

    nestedScrollView.setVisibility(View.VISIBLE);

}
    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");
                if(starttime!=0) {
                    intent.putExtra("timer",Utility.getMinitues(starttime));
                    handler.postDelayed(this, 1000);
                }else{
                    intent.putExtra("timer","0");
                    intent.putExtra("submit",true);
                    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);


            }
        });
    }


    private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(timerText!=null) {
                timerText.setText(intent.getStringExtra("timer"));
            }

            if(intent.getBooleanExtra("submit",false)){
                timerText.setVisibility(View.GONE);
                timerIcon.setVisibility(View.GONE);
                getSections(false);
            }

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

    @Override
    protected void onResume() {
        super.onResume();
        myRequestQueue=MyRequestQueue.getInstance(this);
        registerReceiver(broadcastReceiver,new IntentFilter("spottest.timer"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
//        //--swathi--//
//        SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
//        SharedPreferences.Editor editor = prefs.edit();
//        editor.putString("lastActivity", getClass().getName());
//        editor.apply();
//        //--swathi--//
    }

    private void getWidgets(){
//        Toast.makeText(this,"getWidgets()",Toast.LENGTH_SHORT).show();
        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.cameraButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCamera();
            }
        });

        gestureOverlayView=findViewById(R.id.gestureOverlayView);
        nestedScrollView=findViewById(R.id.scrollView);
        nestedScrollView.setVisibility(View.GONE);
        gestureOverlayView.setDrawingCacheEnabled(true);

        gestureOverlayView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                nestedScrollView.requestDisallowInterceptTouchEvent(true);//very important
                return false;
            }
        });

        findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gestureOverlayView.clear(false);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_section, menu);
        doneitem = menu.findItem(R.id.done);
        doneitem.setEnabled(true);
        doneitem.getIcon().setAlpha(255);
        refreshitem = menu.findItem(R.id.refresh);
        if(refreshstate == true)
        {
            refreshitem.setVisible(true);
        }
        else
        {
            refreshitem.setVisible(false);
        }
        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) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User clicked OK button
                    dialog.dismiss();
                    MySnackbar.getInstance(SectionsActivity.this).dismiss();
                    //invalidateOptionsMenu();
                    doneitem.setEnabled(false);
                    doneitem.getIcon().setAlpha(130);
                    submitAnswer();
                }
            });

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

            builder.setMessage("Do you want to really submit?");

            AlertDialog dialog = builder.create();
            dialog.setCancelable(false);
            dialog.show();
//            MySnackbar.getInstance(this).dismiss();
//            submitAnswer();
        }
         if(id == R.id.refresh)
         {
             refreshlogic();

         }
        return super.onOptionsItemSelected(item);
    }
//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
////        if (isFinalized) {
////            //menu.getItem(0).setVisible(false);
////            menu.findItem(R.id.done).setEnabled(false);
////        }
//        MenuItem item = menu.findItem(R.id.done);
//
//        if (myItemShouldBeEnabled) {
//            item.setEnabled(true);
//            item.getIcon().setAlpha(255);
//        } else {
//            // disabled
//            item.setEnabled(false);
//            item.getIcon().setAlpha(130);
//        }
//        return super.onPrepareOptionsMenu(menu);
//    }
    private void openCamera(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = getOutputMediaFileUri();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, CAPTURE_NUMBER);
    }

    public Uri getOutputMediaFileUri() {
        //return FileProvider.getUriForFile(this,BuildConfig.APPLICATION_ID + ".provider",getOutputMediaFile(type));

        mediaFile= Utility.getCapturedImageFile();
        Uri uri= null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID + ".provider",
                    Objects.requireNonNull(mediaFile));
            Log.d("Androdid","n");
        }else{
            uri= Uri.fromFile(mediaFile);
            Log.d("Androdid","below n");
        }
        //  uri= Uri.fromFile(mediaFile);
        return uri;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //processImage(resultCode,requestCode);
        if (requestCode == CAPTURE_NUMBER && resultCode == RESULT_OK) {

            Bitmap bitmap = null;
            Uri uri=imageUri;

            if(uri!=null) {
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, null);
                    bitmap = Utility.processImage(bitmap);
                    camString=Utility.bitmap2string(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                snapshot.setImageBitmap(bitmap);
            }
        }
        if (mediaFile != null) {
            mediaFile.delete();
        }
    }

    private void submitAnswer(){
        DataBase checkdataBase=new DataBase(this);
        int answercount = checkdataBase.getAnswerscount(assignId);
        if(answercount!=0) {
            isSubmiting = true;
            final DataBase dataBase = new DataBase(this);

            Map<String, String> params = new HashMap<>();
            params.put("email", Preference.getInstance(this).getStudentId());
            params.put("assignId", assignId);
            params.put("json", dataBase.getAnswers(assignId).toString());
            params.put("json_dontknow", dataBase.getAnswers_dontknow(assignId).toString());
            params.put("camera", camString);
            if (gestureOverlayView.getDrawingCache() == null) {
                params.put("sign", "");
            } else {
                params.put("sign", Utility.bitmap2string(gestureOverlayView.getDrawingCache()));
            }

            MyRequestQueue myRequestQueue = MyRequestQueue.getInstance(this);
            myRequestQueue.addToQueue(URL.INSERT_ANSWERS, params, new MyRequestQueue.MyRequestFinishedListener() {
                @Override
                public void requestResult(String response) {
                    stopService(new Intent(getApplicationContext(), MoniterService.class));
                    try {
                        isSubmiting = false;
                        JSONObject jsonObject = new JSONObject(response);
                        //  Toast.makeText(SectionsActivity.this,"inserted_dontknow="+jsonObject.getInt("inserted_dontknow"),Toast.LENGTH_LONG).show();
//                        if (jsonObject.getInt("inserted") == 1) {
//                            dataBase.deleteAnswered(assignId);
//                        }
                        if (jsonObject.getInt("inserted") == 1 && jsonObject.getInt("updated") == 1) {
                           dataBase.deleteAnswered(assignId);
                            Toast.makeText(getApplicationContext(), "Submitted Sucessfully", Toast.LENGTH_SHORT).show();
                            //--swathi--//I placed here also,bcoz in few papers,once questions submitted,it may or may not go to resultactivity according to logic
                            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
                            SharedPreferences.Editor editor = prefs.edit();
                            editor.putString("lastActivity", ResultActivity.class.getName());
                            editor.apply();
//        Toast.makeText(getApplicationContext(), "2="+prefs.getString("lastActivity", SplashActivity.class.getName()),Toast.LENGTH_SHORT).show();
                            //--swathi--//
                            if (showResult) {
                                Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
                                intent.putExtra("assignid", assignId);
                                startActivity(intent);
                            }
                            doneitem.setEnabled(false);
                            doneitem.getIcon().setAlpha(130);
                            finish();
                        } else {
                            doneitem.setEnabled(true);
                            doneitem.getIcon().setAlpha(255);
                            Toast.makeText(getApplicationContext(), "Not Updated,please submit again", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        doneitem.setEnabled(true);
                        doneitem.getIcon().setAlpha(255);
                        //  Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        else {
            Toast.makeText(getApplicationContext(), "You are not allowed to complete the exam without answering even one question", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isValid(){
        if(camString.isEmpty()){
            MySnackbar.getInstance(this).show("Please Take Selfie");
            return false;
        }

        if(gestureOverlayView.getDrawingCache()==null){
            MySnackbar.getInstance(this).show("Please Make Signature");
            return false;
        }
        return true;
    }

    private void alertSubmit(){
        if(isSubmiting){
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

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

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

        builder.setMessage("Test Time Is Over,Please Submit");

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

    private void alert(String string){
        if(isSubmiting){
            return;
        }
        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();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
//--swathi--
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

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

            }
        });


        //builder.setTitle("Time Up");

        builder.setMessage("Do you want to go back?If yes,Please submit the paper.");

        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }
    private void refreshlogic()
    {
        if(isNetworkAvailable()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

// Add the buttons
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User clicked OK button
//                    final DataBase refreshdataBase = new DataBase(SectionsActivity.this);
//                    refreshdataBase.deletequestions(assignId);
//                    refreshdataBase.deleteoptions(assignId);
//                    refreshdataBase.deleteAnswered(assignId);
                    getSections(true);
                    startService();

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

                }
            });


            //builder.setTitle("Time Up");

            builder.setMessage("Do you want to refresh?");

            AlertDialog dialog = builder.create();
            dialog.setCancelable(false);
            dialog.show();
        }else
        {
            Toast.makeText(SectionsActivity.this,"It seems you are not connected to network,please enable it.",Toast.LENGTH_LONG).show();
        }

    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(SectionsActivity.this.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    private void alertdiaolg(String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.dismiss();
                if(isNetworkAvailable())
                {
                    getSections(true);
                }
                else {
                    alertdiaolg("Please check internet connection");
                }
            }
        });
        builder.setMessage(message);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }
    //--swathi--

}
