package com.b2lmobitech.spottest.frags;


import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
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.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

import com.b2lmobitech.spottest.BuildConfig;
import com.b2lmobitech.spottest.R;
import com.b2lmobitech.spottest.encaps.Answer;
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.Utility;

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

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Locale;

import static android.app.Activity.RESULT_OK;


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

    LinearLayout mainLayout;
    NestedScrollView scrollView;
    Button button;
    JSONObject jsonObject=new JSONObject(),tempjosn=new JSONObject();
    private static final int CAPTURE_NUMBER=2;
    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<>();

    public PreviewFragment() {}

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

        assignId=getArguments().getString("assignId");
        sectionId=getArguments().getString("id");
        questionArray=dataBase.getQuestions(sectionId,assignId);

        ArrayList<Answer> arrayList=dataBase.getAnswers(sectionId,assignId);

        for(Answer answer:arrayList){
            Log.d("answers",answer.toString());
            try {
                JSONObject answerObject=new JSONObject();
                answerObject.put("id",answer.getOptionId());
                answerObject.put("name",answer.getOption());
                jsonObject.put(answer.getQuestionId(),answerObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        addViews();
        return view;
    }

    private void getWidgets(View view){
        mainLayout=view.findViewById(R.id.mainLayout);
        button=view.findViewById(R.id.submit_button);
        scrollView=view.findViewById(R.id.scrollView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        button.setVisibility(View.GONE);
        nestedScrollView=view.findViewById(R.id.scrollView);
    }

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

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

            if(str.equalsIgnoreCase(INPUTTYPES.CAMERA) || str.equalsIgnoreCase(INPUTTYPES.SIGNATURE)){
                addImageView(question,i);
            }else if(str.equalsIgnoreCase(INPUTTYPES.DATETIME) || str.equalsIgnoreCase(INPUTTYPES.DATE)
                    ||  str.equalsIgnoreCase(INPUTTYPES.TIME)){
                addDatetime(question,i);
            }else if(str.equalsIgnoreCase(INPUTTYPES.EDIITEXT) || str.equalsIgnoreCase(INPUTTYPES.CHECKBOX)
                     || str.equalsIgnoreCase(INPUTTYPES.SPINNER)
                    || str.equalsIgnoreCase(INPUTTYPES.RADIOBOX)){
                addNonImageView(question,i);
            }
           // addDivider();
            i++;
        }
    }

    private void addDivider(){
        View view=new View(getActivity());
        view.setBackgroundColor(Color.DKGRAY);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,1));
        mainLayout.addView(view);

    }

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

        View view=getLayoutInflater().inflate(R.layout.model_nonimage,mainLayout,false);
        TextView title=view.findViewById(R.id.pre_question);
        title.setText(i+"."+question.getQuestionName());
        TextView answer=view.findViewById(R.id.pre_answer);
        try {
            answer.setText(jsonObject.getJSONObject(question.getQuestionId()).getString("name"));
        } catch (JSONException e) {
            answer.setText("Not Answered");
            answer.setTextColor(Color.RED);
            e.printStackTrace();
        }
        ImageView imageView=view.findViewById(R.id.edit);

        imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAlertDialog(question);
                }
            });

        mainLayout.addView(view);
    }

    private void addImageView(final Question question,int i){
        View view=getLayoutInflater().inflate(R.layout.model_imge,mainLayout,false);
        TextView title=view.findViewById(R.id.pre_question);
        title.setText(i+"."+question.getQuestionName());
        final ImageView snappedImage=view.findViewById(R.id.pre_image);
        try {
            snappedImage.setImageBitmap(Utility.bitmap(jsonObject.getJSONObject(question.getQuestionId()).getString("name")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ImageView edit=view.findViewById(R.id.edit);

        if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.CAMERA)) {
            edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    imageUri = getOutputMediaFileUri();
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CAPTURE_NUMBER);
                    cameraQuestionId = question.getQuestionId();
                    imageView = snappedImage;
                }
            });
        }else {
            edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAlertDialog(question);
                }
            });
        }
        mainLayout.addView(view);
    }

    private void addDatetime(final Question question,int i){
        View view=getLayoutInflater().inflate(R.layout.model_nonimage,mainLayout,false);
        TextView title=view.findViewById(R.id.pre_question);
        title.setText(i+"."+question.getQuestionName());
        TextView answer=view.findViewById(R.id.pre_answer);
        try {
            answer.setText(jsonObject.getJSONObject(question.getQuestionId()).getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ImageView imageView=view.findViewById(R.id.edit);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datetime(question);
            }
        });
        mainLayout.addView(view);
    }

    private void showAlertDialog(Question question){
        String str= question.getQuestionType();
        if(str.equalsIgnoreCase(INPUTTYPES.EDIITEXT)){
            editText(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.CHECKBOX)){
            checkBox(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.DATETIME)){
            datetime(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.SPINNER)){
            setSpinner(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.STAR_RATING)){
            setRatingBar(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.RADIOBOX)){
            radioBox(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.SIGNATURE)){
            setSignature(question);
        }else if(str.equalsIgnoreCase(INPUTTYPES.CAMERA)){
            camera(question);
        }
    }

    private void checkBox(final Question question){

        final HashSet<String> selectedSet=new HashSet<>();
        View view=getLayoutInflater().inflate(R.layout.model_checkbox,null);
        TextView title=view.findViewById(R.id.cb_title);
        title.setText(question.getQuestionName());
        LinearLayout linearLayout=view.findViewById(R.id.check_layout);

        for(final Option option: dataBase.getOptions(question.getQuestionId(),assignId)){
            final CheckBox checkBox=new CheckBox(getActivity());
            checkBox.setText(option.getOptionName());
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if(isChecked){
                        selectedSet.add(option.getOptionName());
                    }else if(selectedSet.contains(option.getOptionName())){
                        selectedSet.remove(option.getOptionName());
                    }
                    String answer=selectedSet.toString().replace("[","").replace("]","");

                    try {
                        tempjosn=new JSONObject();
                        tempjosn.put("id",option.getOptionId());
                        tempjosn.put("name",answer);
                        tempjosn.put("value",option.getValue());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            try {
                if(jsonObject.getJSONObject(question.getQuestionId()).getString("name").toLowerCase().contains(option.getOptionName().toLowerCase())){
                    checkBox.setChecked(true);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            linearLayout.addView(checkBox);
        }
        setAlertListeners(question,view);
    }

    private void radioBox(final Question question){

        // View alert_view=

        View view=getLayoutInflater().inflate(R.layout.model_radiobox,null);
        TextView title=view.findViewById(R.id.cb_title);
        title.setText(question.getQuestionName());
        RadioGroup radioGroup=view.findViewById(R.id.radio_group);

        for(final Option option: dataBase.getOptions(question.getQuestionId(),assignId)){
            RadioButton radioButton = new RadioButton(getActivity());
            radioButton.setText(option.getOptionName());
            radioButton.setGravity(Gravity.CENTER_VERTICAL);
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 5, 0, 5);
            radioButton.setLayoutParams(params);

            radioGroup.addView(radioButton);
            radioButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        tempjosn=new JSONObject();
                        tempjosn.put("id",option.getOptionId());
                        tempjosn.put("name",option.getOptionName());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            try {
                if(jsonObject.getJSONObject(question.getQuestionId()).getString("id").equalsIgnoreCase(option.getOptionId())){
                    radioButton.setChecked(true);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        setAlertListeners(question,view);
    }

    private void editText(final Question question){

        View view=getLayoutInflater().inflate(R.layout.model_edittext,null);
        TextView title=view.findViewById(R.id.text_title);
        EditText editText=view.findViewById(R.id.text_input);
        title.setText(question.getQuestionName());
        try {
            editText.setText(jsonObject.getJSONObject(question.getQuestionId()).getString("name"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(question.getFormat().equalsIgnoreCase("email")){
            editText.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
        }else if(question.getFormat().equalsIgnoreCase("phone_number")){
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    tempjosn=new JSONObject();
                    tempjosn.put("id","null");
                    tempjosn.put("name",s);
                    tempjosn.put("value","0");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        setAlertListeners(question,view);

    }

    private void setRatingBar(Question question){
        View view=getLayoutInflater().inflate(R.layout.model_rating,mainLayout,false);
        TextView title=view.findViewById(R.id.text_title);
        RatingBar ratingBar=view.findViewById(R.id.rating_bar);
        title.setText(question.getQuestionName());
        ratingBar.setNumStars(Integer.parseInt(question.getLimitMax()));
        mainLayout.addView(view);
    }

    private void setSpinner(Question question){
        View view=getLayoutInflater().inflate(R.layout.model_spinner,mainLayout,false);
        TextView title=view.findViewById(R.id.text_title);
        Spinner spinner=view.findViewById(R.id.spinner);
        title.setText(question.getQuestionName());

        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, question.getOptions()); //selected item will look like a spinner set from XML
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerArrayAdapter);

        mainLayout.addView(view);
    }

    private void setSignature(final Question question){

        View view=getLayoutInflater().inflate(R.layout.model_signature,null);
        TextView title=view.findViewById(R.id.text_title);
        title.setText(question.getQuestionName());
        final GestureOverlayView gues=view.findViewById(R.id.signaturePad);
        Button clearButton=view.findViewById(R.id.clear_sign);

        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gues.clear(true);
            }
        });

        gues.setDrawingCacheEnabled(true);



        gues.addOnGestureListener(new GestureOverlayView.OnGestureListener() {
            @Override
            public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {

            }

            @Override
            public void onGesture(GestureOverlayView overlay, MotionEvent event) {

            }

            @Override
            public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
                if(overlay.getDrawingCache()!=null) {


                    try {
                        tempjosn = new JSONObject();
                        tempjosn.put("id", "null");
                        tempjosn.put("name", Utility.imgToString(overlay.getDrawingCache()));
                        tempjosn.put("value", "0");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event) {

            }
        });
        setAlertListeners(question,view);
    }

    private void camera(final Question question){

        View view=getLayoutInflater().inflate(R.layout.model_camera,null);
        TextView title=view.findViewById(R.id.text_title);
        Spinner spinner=view.findViewById(R.id.spinner);
        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) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                imageUri = getOutputMediaFileUri();
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, CAPTURE_NUMBER);
                cameraQuestionId=question.getQuestionId();
                imageView=snappedImage;
            }
        });
        mainLayout.addView(view);

    }

    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(getActivity(),
                    BuildConfig.APPLICATION_ID + ".provider",
                    mediaFile);
            Log.e("Androdid","n");
        }else{
            uri= Uri.fromFile(mediaFile);
            Log.e("Androdid","below n");
        }
        //  uri= Uri.fromFile(mediaFile);
        return uri;
    }

    private void datetime(final Question question){

        if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.DATE)){
            setDatePicker(question.getQuestionId());
        }else if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.DATETIME)){
            setDateTimePicker(question.getQuestionId());
        }else if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.TIME)){
            setTimePicker(question.getQuestionId());
        }
    }

    private void setDatePicker(final String questionId){
        final Calendar myCalendar= Calendar.getInstance();

        final DatePickerDialog.OnDateSetListener listenr = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                String myFormat = "dd/MM/yyyy"; //In which you need put here
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                try {
                    tempjosn=new JSONObject();
                    tempjosn.put("id","null");
                    tempjosn.put("name",sdf.format(myCalendar.getTime()));
                    tempjosn.put("value","0");
                    jsonObject.put(questionId,tempjosn);
                    tempjosn=new JSONObject();
                    addViews();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        };
        DatePickerDialog datePicker =  new DatePickerDialog(getActivity(), listenr, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH));
        datePicker.show();
    }

    private void setTimePicker(final String questionId){
        final Calendar myCalendar= Calendar.getInstance();
        int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = myCalendar.get(Calendar.MINUTE);
        final TimePickerDialog.OnTimeSetListener listenr = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                myCalendar.set(Calendar.HOUR, hourOfDay);
                myCalendar.set(Calendar.MINUTE, minute);
                String myFormat = "HH:mm:ss"; //In which you need put here
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                try {
                    tempjosn=new JSONObject();
                    tempjosn.put("id","null");
                    tempjosn.put("name",sdf.format(myCalendar.getTime()));
                    tempjosn.put("value","0");
                    jsonObject.put(questionId,tempjosn);
                    tempjosn=new JSONObject();
                    addViews();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        };
        TimePickerDialog timePickerDialog=new TimePickerDialog(getActivity(),listenr,hour, minute, true);
        timePickerDialog.show();
    }

    private void setDateTimePicker(final String questionId){

        final Calendar myCalendar= Calendar.getInstance();

        int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = myCalendar.get(Calendar.MINUTE);
        final TimePickerDialog.OnTimeSetListener listenr2 = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                myCalendar.set(Calendar.HOUR, hourOfDay);
                myCalendar.set(Calendar.MINUTE, minute);
                String myFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                try {
                    tempjosn=new JSONObject();
                    tempjosn.put("id","null");
                    tempjosn.put("name",sdf.format(myCalendar.getTime()));
                    tempjosn.put("value","0");
                    jsonObject.put(questionId,tempjosn);
                    tempjosn=new JSONObject();
                    addViews();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        };
        final TimePickerDialog timePickerDialog=new TimePickerDialog(getActivity(),listenr2,hour, minute, true);

        final DatePickerDialog.OnDateSetListener listenr = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                timePickerDialog.show();
            }

        };
        DatePickerDialog datePicker =  new DatePickerDialog(getActivity(), listenr, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH));
        datePicker.show();
    }

    private void setAlertListeners(final Question question, View view){

        View dialogView =getLayoutInflater().inflate(R.layout.model_alert, null);
        final LinearLayout linearLayout=dialogView.findViewById(R.id.alert_layout);
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
        dialogBuilder.setView(dialogView);
        final AlertDialog alertDialog = dialogBuilder.create();
        linearLayout.addView(view);
        final Button button= dialogView.findViewById(R.id.model_submit);

        button.findViewById(R.id.model_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(tempjosn.getString("name").isEmpty()){
                        return;
                    }
                    jsonObject.put(question.getQuestionId(),tempjosn);
                    tempjosn=new JSONObject();
                    linearLayout.removeAllViews();
                    addViews();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                alertDialog.dismiss();
            }
        });

        dialogView.findViewById(R.id.model_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                linearLayout.removeAllViews();
            }
        });
        alertDialog.setCancelable(false);
        alertDialog.show();

    }

    public void submitAnswer(){
        insertInLocal(assignId);
        getActivity().finish();
    }

    private void insertInLocal(String assignId){
        for(Question question :questionArray) {
            try {
                JSONObject answerJson=jsonObject.getJSONObject(question.getQuestionId());
                if(answerJson.length()!=0){
                    boolean isBlob=false;
                    if(question.getQuestionType().equalsIgnoreCase(INPUTTYPES.CAMERA) ||
                            question.getQuestionType().equalsIgnoreCase(INPUTTYPES.SIGNATURE) ){
                        isBlob=true;
                    }
                    dataBase.insertAnswer(question.getQuestionId(),question.getSectionId(),assignId,answerJson.getString("name"),answerJson.getString("id"),isBlob);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

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

            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 {
                    JSONObject answerJson=new JSONObject();
                    answerJson.put("id","image");
                    answerJson.put("name",Utility.bitmap2string(bitmap));
                    jsonObject.put(cameraQuestionId,answerJson);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
        if (mediaFile != null) {
            mediaFile.delete();
        }
    }

}
