package com.b2lmobitech.spottest.frags;


import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
//import android.support.v13.app.FragmentCompat;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.NestedScrollView;
import android.text.Editable;
import android.text.InputType;
import android.text.Layout;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.b2lmobitech.spottest.network.MyRequestQueue;
import com.b2lmobitech.spottest.network.URL;
import com.b2lmobitech.spottest.radio.RadioImageButton;
import com.aagito.imageradiobutton.RadioImageGroup;
import com.b2lmobitech.spottest.BuildConfig;
import com.b2lmobitech.spottest.R;
import com.b2lmobitech.spottest.encaps.Option;
import com.b2lmobitech.spottest.encaps.Question;
import com.b2lmobitech.spottest.sql.DataBase;
import com.b2lmobitech.spottest.utils.INPUTTYPES;
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.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;


/**
 * A simple {@link Fragment} subclass.
 */
public class SingleQuestionFragment extends Fragment {

    LinearLayout mainLayout;
    NestedScrollView scrollView;
    Button button;
    JSONObject jsonObject=new JSONObject();
    private static final int CAPTURE_NUMBER=100;
    private static final int  MY_CAMERA_REQUEST_CODE =500;
    public static final int REQUEST_CHECK_SETTINGS = 1;
    NestedScrollView nestedScrollView;

    Uri imageUri;
    File mediaFile;
    ImageView imageView;
    String cameraQuestionId,assignId,sectionId;
    DataBase dataBase;

    ArrayList<Question> questionArray=new ArrayList<>();
    private Listener listener;
    ArrayList<Question> skippedList=new ArrayList<>();

    ProgressBar questionProgress;
    TextView questionCount,sectionName,totalcount;
    Button next;
    int totalQuestions,answerdQuestions=0,shownQuestions=0;
    String currentQuestionId;
    int skippedCount=-1;
    boolean iSAlreaySkippedQuesiton=false,isLastQuestion=false;
    public SingleQuestionFragment() {}
    Question question;
    JSONObject answerJson;
    private int questionnumber;
    private static ConnectivityManager cm;
    private View questionview;
//    private static String imageStoragePath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_question_single, container, false);
        getWidgets(view);
        questionview = view;
        dataBase=new DataBase(getActivity());

        assignId=getArguments().getString("assignId");
        sectionId=getArguments().getString("id");
        cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        questionnumber = 1;
        totalQuestions=dataBase.getQuestions(sectionId,assignId).size();
        answerdQuestions=dataBase.getAnswers(sectionId,assignId).size();
        questionArray=dataBase.getQuestionInRandomOrder(sectionId,assignId);
        questionProgress.setMax(totalQuestions);

        //addViews();
        question=questionArray.get(0);
        showNextQuestion(questionArray.get(shownQuestions));

        return view;
    }

    private void insertAnswer(){
        try {
            boolean isBlob=false;
            if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.CAMERA) ||
                    question.getQuestionType().equalsIgnoreCase(INPUTTYPES.SIGNATURE) ){
                isBlob=true;
            }
            dataBase.insertAnswer(question.getQuestionId(),sectionId,assignId,answerJson.getString("name"),answerJson.getString("id"),isBlob);
        } catch (JSONException e) {
            e.printStackTrace();
            //skippedList.add(questionArray.get(shownQuestions));
            dataBase.insertAnswer(question.getQuestionId(),sectionId,assignId,"","",false);
        }

        if(isLastQuestion){
            getActivity().finish();
        }

        answerdQuestions=dataBase.getAnswers(sectionId,assignId).size();
        isLastQuestion = (answerdQuestions + 1) == totalQuestions;

        if((shownQuestions+1)==questionArray.size()){
            if(skippedList.size()==0 || (skippedCount+1)==skippedList.size()){
                getActivity().finish();
            }else{
                skippedCount++;
                question=skippedList.get(skippedCount);
                iSAlreaySkippedQuesiton=true;
            }
        }else{
            iSAlreaySkippedQuesiton=false;
            shownQuestions++;
            question=questionArray.get(shownQuestions);
        }
        showNextQuestion(question);
    }

    private void getWidgets(View view){
        mainLayout=view.findViewById(R.id.mainLayout);
        next=view.findViewById(R.id.next);
        questionCount=view.findViewById(R.id.questionCount);
        totalcount =view.findViewById(R.id.totalCount);
        sectionName=view.findViewById(R.id.sectionName);
        questionProgress=view.findViewById(R.id.questionProgress);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertAnswer();
            }
        });

        //scrollView=view.findViewById(R.id.scrollView);
        //nestedScrollView=view.findViewById(R.id.scrollView);

    }

    private void showNextQuestion(Question question){
        questionProgress.setProgress(answerdQuestions);
        questionCount.setText("Question : "+questionnumber);//"Answered "+answerdQuestions+" of "+totalQuestions
        totalcount.setText(" Total : "+totalQuestions);

        mainLayout.removeAllViews();
        answerJson=new JSONObject();
        currentQuestionId=question.getQuestionId();
        int i=shownQuestions;
        String str= question.getQuestionType();
        if(str.equalsIgnoreCase(INPUTTYPES.RADIOBOX)){
            radioBox(question,i);
            //camera(question,i);
        }else if(str.equalsIgnoreCase(INPUTTYPES.CAMERA)){
            camera(question,i);
        }
        try {
            jsonObject.put(question.getQuestionId(),new JSONObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(isLastQuestion || totalQuestions==1 || questionArray.size()==1){
            next.setText("SUBMIT");
            next.setBackgroundColor(getActivity().getResources().getColor(R.color.buttonDisabled));
            next.setEnabled(false);
        }

            if (iSAlreaySkippedQuesiton) {
//                if(isLastQuestion || totalQuestions==1 || questionArray.size()==1){
//                    next.setText("SUBMIT");
//                    next.setBackgroundColor(getActivity().getResources().getColor(R.color.buttonDisabled));
//                    next.setEnabled(false);
//                }
//               else
//                {
                    next.setText("NEXT");
                    next.setBackgroundColor(getActivity().getResources().getColor(R.color.buttonDisabled));
                    next.setEnabled(false);
//                }

            } else {

                    next.setText("DON'T KNOW");
                    next.setBackgroundColor(getActivity().getResources().getColor(R.color.colorPrimaryDark));
                    next.setEnabled(true);


            }

           if(totalQuestions>questionnumber)
           {
               questionnumber =  questionnumber+1;
           }

    }

    private void addViews(){
        int i=1;
        dataBase=new DataBase(getActivity());

    for(Question question :questionArray) {
            String str= question.getQuestionType();

            if(str.equalsIgnoreCase(INPUTTYPES.RADIOBOX)){
                radioBox(question,i);
            }else if(str.equalsIgnoreCase(INPUTTYPES.CAMERA)){
                camera(question,i);
            }

            try {
                jsonObject.put(question.getQuestionId(),new JSONObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }

            i++;
        }
    }

    private void radioBox(final Question question,final int i){

        View view=getLayoutInflater().inflate(R.layout.model_radiobox,mainLayout,false);
        TextView title=view.findViewById(R.id.cb_title);
        title.setText(question.getQuestionName());
        RadioImageGroup radioGroup=view.findViewById(R.id.radioGroup);
        radioGroup.setOrientation(LinearLayout.VERTICAL);
        ArrayList<Option> arrayList=dataBase.getOptions(question.getQuestionId(),assignId);
        Button downloadbutton=view.findViewById(R.id.Download);

        if(arrayList.size()==0)
        {
         //   Toast.makeText(getActivity(),"download button = "+arrayList.size(),Toast.LENGTH_LONG).show();
            downloadbutton.setVisibility(View.VISIBLE);
            next.setVisibility(View.INVISIBLE);
        }
        else
        {
            downloadbutton.setVisibility(View.GONE);
            next.setVisibility(View.VISIBLE);
//            Toast.makeText(getActivity(),"options size = "+arrayList.size(),Toast.LENGTH_LONG).show();
        }
        downloadbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isNoNetwork())
                {

                }
                else {
                    getmissedOptions(question.getQuestionId(), question, i, mainLayout, view);
                }
            }
        });
        for(final Option option: arrayList){
            final RadioImageButton radioButton = new RadioImageButton(getActivity());

            TextView textView=radioButton.findViewById(R.id.textView);
            textView.setText(option.getOptionName());

            ViewGroup.LayoutParams layoutParams=radioButton.getLayoutParams();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(0, 10, 0, 0);
            radioButton.setLayoutParams(params);

            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {
                        answerJson=new JSONObject();
                        answerJson.put("id",option.getOptionId());
                        answerJson.put("name",option.getOptionName());
                        Log.d("json",answerJson.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if(isLastQuestion ){
                        if(listener!=null){
                            listener.EnableSubmit();
                        }
                        next.setText("SUBMIT");
                    }
                    else{
                        next.setText("NEXT");
                    }
                     //Dont forget this line

                    next.setBackgroundColor(getActivity().getResources().getColor(R.color.colorPrimaryDark));
                    next.setEnabled(true);
                    //insertAnswer();
                }
            });

            radioGroup.addView(radioButton);
        }
        mainLayout.addView(view);

    }

    private void camera(final Question question,int i){
        View view=getLayoutInflater().inflate(R.layout.model_camera,mainLayout,false);
        TextView title=view.findViewById(R.id.text_title);
        title.setText(question.getQuestionName());

        ImageView openCamera=view.findViewById(R.id.openCamera);
        final ImageView snappedImage=view.findViewById(R.id.snapped_image);
        openCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
//                        == PackageManager.PERMISSION_GRANTED) {
//                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//                    startActivityForResult(cameraIntent, CAPTURE_NUMBER);
//                }
                try {
//                if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.CAMERA)
//                        == PackageManager.PERMISSION_GRANTED) {
//                    Toast.makeText(getActivity(),"granted",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                    if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
//                    Intent intent = new Intent();
//                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
//                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    Uri imageUri = getOutputMediaFileUri();
                 //   Toast.makeText(getActivity(), "imageUri=" + imageUri, Toast.LENGTH_SHORT).show();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//                        try {
                    startActivityForResult(intent, CAPTURE_NUMBER);//getParentFragment().
//                }
//                else
//                {
//                    Toast.makeText(getActivity(),"not granted",Toast.LENGTH_SHORT).show();
//                }
                        }catch(Exception e)
                        {
                            Toast.makeText(getActivity(), "error=" +e.toString(), Toast.LENGTH_SHORT).show();
                        }

                    cameraQuestionId = question.getQuestionId();
                    imageView = snappedImage;
                    if (listener != null) {
                        listener.RequestStarted();
                    }

            }
        });
        mainLayout.addView(view);

    }

//    public Uri getOutputMediaFileUri() {
//        //return FileProvider.getUriForFile(this,BuildConfig.APPLICATION_ID + ".provider",getOutputMediaFile(type));
//        Uri uri = null;
//
//    mediaFile = Utility.getCapturedImageFile();
//
////        if (mediaFile != null) {
////            imageStoragePath = mediaFile.getAbsolutePath();
////        }
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//
//        uri = FileProvider.getUriForFile(getActivity(),
//                BuildConfig.APPLICATION_ID + ".provider",
//                mediaFile);//getActivity()
//
//        Log.e("Androdid", "n");
//    } else {
//        uri = Uri.fromFile(mediaFile);
//        Log.e("Androdid", "below n");
//    }
//    //  uri= Uri.fromFile(mediaFile);
//
//        return uri;
//    }

    public void submitAnswer(){
        isLastQuestion=true;
        insertAnswer();
        //getActivity().finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
//            Toast.makeText(getActivity(), "requestCode=" + requestCode, Toast.LENGTH_SHORT).show();
//
//        Toast.makeText(getActivity(),"resultCode="+resultCode,Toast.LENGTH_SHORT).show();

//        Toast.makeText(getActivity(),"imageStoragePath="+imageStoragePath,Toast.LENGTH_SHORT).show();
        if(listener !=null){
            listener.RequestFinished();
        }
        if (requestCode == CAPTURE_NUMBER ) {
            if( resultCode == RESULT_OK){
            //Toast.makeText(getActivity(),"",Toast.LENGTH_SHORT).show();
            //refresh the gallery
//            Utility.refreshGallery(getActivity(), imageStoragePath);
            Bitmap bitmap = null;
            Uri uri = imageUri;

            if (uri != null) {
                try {
                    bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri), null, null);
                    bitmap = Utility.processImage(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                imageView.setImageBitmap(bitmap);
                try {
                    answerJson = new JSONObject();
                    answerJson.put("id", "image");
                    answerJson.put("name", Utility.bitmap2string(bitmap));
                    answerJson.put("value", "0");
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                if (isLastQuestion || totalQuestions == 1 || questionArray.size() == 1) {
                    next.setText("SUBMIT");
                    next.setBackgroundColor(getActivity().getResources().getColor(R.color.buttonDisabled));
                    next.setEnabled(false);
                    if (listener != null) {
                        listener.EnableSubmit();
                    }

                } else {
                    next.setText("NEXT");
                    next.setEnabled(true);
                }

                next.setBackgroundColor(getActivity().getResources().getColor(R.color.colorPrimaryDark));
                next.setEnabled(true);

            }
        }
            else if(resultCode == RESULT_CANCELED)
            {
                Toast.makeText(getActivity(),"You cancelled Image capture",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(getActivity(),"Sorry!Failed to capture image",Toast.LENGTH_SHORT).show();
            }
        }
        if (mediaFile != null) {
            mediaFile.delete();
        }
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public interface Listener {
        void RequestStarted();
        void RequestFinished();
        void EnableSubmit();
    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
//        if (requestCode == MY_CAMERA_REQUEST_CODE) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
//                Toast.makeText(getActivity(), "camera permission granted", Toast.LENGTH_LONG).show();
//            } else {
//                Toast.makeText(getActivity(), "camera permission denied", Toast.LENGTH_LONG).show();
//            }
//        }
//    }
//    public void onActivityResult(int requestCode, int resultCode, Intent data)
//    {
//        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
//        {
//            Bitmap photo = (Bitmap) data.getExtras().get("data");
//            imageView.setImageBitmap(photo);
//        }
//    }
private Uri getOutputMediaFileUri()
    {
        File mediaFile = null;
        File mediaStorageDir = new File("/sdcard/Android/data/com.b2lmobitech.spottest/"+"Spottestimages");
        if(!mediaStorageDir.exists())
        {
            if(!mediaStorageDir.mkdirs())
            {
              return  null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        mediaFile = new File(mediaStorageDir.getPath() + File.separator

                + "IMG_" + System.currentTimeMillis() + ".jpg");//timeStamp
        try {
            //mediaFile.getParentFile().mkdirs();
            mediaFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            return  FileProvider.getUriForFile(getContext(),
                    BuildConfig.APPLICATION_ID + ".provider",
                    mediaFile);//getActivity()

//            Log.e("Androdid", "n");
        } else {
            return Uri.fromFile(mediaFile);
//            Log.e("Androdid", "below n");
        }
        //  uri= Uri.fromFile(mediaFile);


    }
//----get_missedoptions--

    private void getmissedOptions(String missedquestionid, final Question questionvalue, final int ivalue,final LinearLayout mainlayoutvalue, final View viewvalue) {
        final DataBase dataBase=new DataBase(getActivity());

        Map<String, String> params = new HashMap<>();
        params.put("email", Preference.getInstance(getActivity()).getStudentId());
        params.put("question_id", missedquestionid);
        params.put("assignId", assignId);
        final MyRequestQueue myRequestQueue=MyRequestQueue.getInstance(getActivity());
        myRequestQueue.addToQueue(URL.GET_MissedOPTIONS, 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(getActivity(), "optioncheck=" + optioncheck, Toast.LENGTH_LONG).show();
                            if (optioncheck != 1) {
                                Toast.makeText(getActivity(), "It seems your options for this question are 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();
                                mainlayoutvalue.removeAllViews();
                                next.setVisibility(View.VISIBLE);
                                radioBox(questionvalue,ivalue);
                            }
                        }
//                        else
//                        {
//                            Toast.makeText(SectionsActivity.this, "option object null", Toast.LENGTH_LONG).show();
//                        }
                    }
//                    else
//                    {
//                        Toast.makeText(SectionsActivity.this, "In get_option 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, "error get_option It seems your data is not downloaded,please click refresh button", Toast.LENGTH_LONG).show();
//                    refreshstate = true;
//                    invalidateOptionsMenu();
                }
            }
        });
    }
    //---get_missedoptions--
    public boolean isNoNetwork() {
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            return false;
        }else{
            Toast.makeText(getActivity(),"No Inernet Connection",Toast.LENGTH_SHORT).show();
            return true;
        }
    }

}
