package com.pixelnx.sam.jobportal.Fragment;
import android.annotation.SuppressLint;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.StringRequestListener;
import com.androidnetworking.interfaces.UploadProgressListener;
import com.cocosw.bottomsheet.BottomSheet;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.pixelnx.sam.jobportal.Activity.SeekerDashboardActivity;
import com.pixelnx.sam.jobportal.DTO.MonthDTO;
import com.pixelnx.sam.jobportal.DTO.UserSeekerDTO;
import com.pixelnx.sam.jobportal.DTO.YearDTO;
import com.pixelnx.sam.jobportal.DTOCI.FetchGeneralData;
import com.pixelnx.sam.jobportal.DTOCI.ModelLanguageDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelSeekerLogin;
import com.pixelnx.sam.jobportal.R;
import com.pixelnx.sam.jobportal.https.UploadFileToServer;
import com.pixelnx.sam.jobportal.network.NetworkManager;
import com.pixelnx.sam.jobportal.preferences.SharedPrefrence;
import com.pixelnx.sam.jobportal.utils.AppConstans;
import com.pixelnx.sam.jobportal.utils.Consts;
import com.pixelnx.sam.jobportal.utils.ConvertUriToFilePath;
import com.pixelnx.sam.jobportal.utils.CustomButton;
import com.pixelnx.sam.jobportal.utils.CustomEdittext;
import com.pixelnx.sam.jobportal.utils.CustomTextSubHeader;
import com.pixelnx.sam.jobportal.utils.CustomTextview;
import com.pixelnx.sam.jobportal.utils.FilePath;
import com.pixelnx.sam.jobportal.utils.ImageCompression;
import com.pixelnx.sam.jobportal.utils.MainFragment;
import com.pixelnx.sam.jobportal.utils.MonthYearPicker;
import com.pixelnx.sam.jobportal.utils.ProjectUtils;

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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;


public class SeekerUpdateProfileFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    private static final String TAG = SeekerUpdateProfileFragment.class.getSimpleName();
    private CircleImageView IVimage;
    private RadioGroup RGGender, RGExperience;
    private RadioButton RBmale, RBfemale;
    private CustomEdittext etEmail, etName, etMobile, etCgpa, etFileUpload, etCurrentAddress, etPassYear, etCertification;
    private Spinner SpPrefLoc, SpJobType, SpQualification, SpAreaOfSector, SpSpecialization, SpRoleType, SpTotalExperienceYear, SpToatlExperienceinMonth;
    private CustomButton btnUpdate;
    SeekerDashboardActivity seekerDashboardActivity = new SeekerDashboardActivity();
    private SharedPrefrence prefrence;
    // GeneralDTO generalDTO;
    private FetchGeneralData generalDTO;
    private CustomTextSubHeader tvUsername;
    private ModelSeekerLogin userSeekerDTOS;
    View view;
    private ArrayList<FetchGeneralData.Data.Location> locationsList = new ArrayList<FetchGeneralData.Data.Location>();
    private ArrayList<FetchGeneralData.Data.Area_of_s> area_of_sectorsList = new ArrayList<FetchGeneralData.Data.Area_of_s>();
    private ArrayList<FetchGeneralData.Data.Qualification> qualificationsList = new ArrayList<FetchGeneralData.Data.Qualification>();
    private ArrayList<FetchGeneralData.Data.JobType> job_typesList = new ArrayList<FetchGeneralData.Data.JobType>();
    private ArrayList<FetchGeneralData.Data.Desi> job_by_roles_List = new ArrayList<FetchGeneralData.Data.Desi>();
    private ArrayList<FetchGeneralData.Data.Specialization> specializationList = new ArrayList<FetchGeneralData.Data.Specialization>();
   // private List<YearDTO> exprinceYearDTOList = new ArrayList<YearDTO>();
 //   private List<MonthDTO> exprinceMonthDTOList = new ArrayList<MonthDTO>();
    private List<FetchGeneralData.Data.Exp> expList = new ArrayList<FetchGeneralData.Data.Exp>();

    private ArrayAdapter<FetchGeneralData.Data.Location> location_Adapter;
    private ArrayAdapter<FetchGeneralData.Data.Area_of_s> aos_Adapter;
    private ArrayAdapter<FetchGeneralData.Data.Qualification> qualification_Adapter;
    private ArrayAdapter<FetchGeneralData.Data.JobType> job_type_Adapter;
    private ArrayAdapter<FetchGeneralData.Data.Desi> job_by_roles_Adapter;
    private ArrayAdapter<FetchGeneralData.Data.Specialization> specialization_Adapter;
    private ArrayAdapter<YearDTO> exprinceYear_adapter;
    private ArrayAdapter<MonthDTO> exprinceMonth_adapter;
    private ArrayAdapter<FetchGeneralData.Data.Exp> exp_adapter;
    ArrayList<File> fileList;
    ArrayList<String> fileListString;
    String resumeString="";


    private DisplayImageOptions options;
    private Calendar myCalendar = Calendar.getInstance();

    Uri picUri, filePath;
    int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
    int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;
    BottomSheet.Builder builder;
    String pathOfImage, pathOfResume, extensionIMG, extensionResume;
    Bitmap bm;
    ImageCompression imageCompression;
    private int PICK_PDF_REQUEST = 5005;

    private MonthYearPicker myp;
    private Typeface font;
    private File image;
    private File resume;
    private String baseUrl="";
    ModelLanguageDTO.Data modelLanguageDTO;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_update_profile_seeker, container, false);
        prefrence = SharedPrefrence.getInstance(getActivity());
        userSeekerDTOS = prefrence.getUserDTO(AppConstans.SEEKERDTO);
        ProjectUtils.initImageLoader(getActivity());
        seekerDashboardActivity.search_icon.setVisibility(View.INVISIBLE);
        seekerDashboardActivity.filter_icon.setVisibility(View.INVISIBLE);
        font = Typeface.createFromAsset(
                SeekerUpdateProfileFragment.this.getActivity().getAssets(),
                "Raleway-Light.ttf");
        init(view);
        baseUrl=userSeekerDTOS.getBase_url();
        tvUsername.setText("" + userSeekerDTOS.getData().getName());
        return view;
    }

    private void init(View view) {


        IVimage = (CircleImageView) view.findViewById(R.id.IVimage);
        etEmail = (CustomEdittext) view.findViewById(R.id.etEmail);
        etName = (CustomEdittext) view.findViewById(R.id.etName);
        etMobile = (CustomEdittext) view.findViewById(R.id.etMobile);
        etCgpa = (CustomEdittext) view.findViewById(R.id.etCgpa);
        etFileUpload = (CustomEdittext) view.findViewById(R.id.etFileUpload);
        etCurrentAddress = (CustomEdittext) view.findViewById(R.id.etCurrentAddress);
        etPassYear = (CustomEdittext) view.findViewById(R.id.etPassYear);
        tvUsername = (CustomTextSubHeader) view.findViewById(R.id.tvUsername);

        SpPrefLoc = (Spinner) view.findViewById(R.id.SpPrefLoc);
        SpJobType = (Spinner) view.findViewById(R.id.SpJobType);
        SpQualification = (Spinner) view.findViewById(R.id.SpQualification);
        SpAreaOfSector = (Spinner) view.findViewById(R.id.SpAreaOfSector);
        SpSpecialization = (Spinner) view.findViewById(R.id.SpSpecialization);
      SpTotalExperienceYear = (Spinner) view.findViewById(R.id.SpTotalExperienceYear);

        RGGender = (RadioGroup) view.findViewById(R.id.RGGender);
        RBmale = (RadioButton) view.findViewById(R.id.RBmale);
        RBfemale = (RadioButton) view.findViewById(R.id.RBfemale);



        btnUpdate = (CustomButton) view.findViewById(R.id.btnUpdate);

        changeLanguage(view);
        SpPrefLoc.setOnItemSelectedListener(this);
        SpJobType.setOnItemSelectedListener(this);
        SpQualification.setOnItemSelectedListener(this);
        SpAreaOfSector.setOnItemSelectedListener(this);
        SpTotalExperienceYear.setOnItemSelectedListener(this);

        etFileUpload.setOnClickListener(this);
        btnUpdate.setOnClickListener(this);
        etPassYear.setOnClickListener(this);
        getSeekerInfo();
        etCgpa.setFilters(new InputFilter[]{
                new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
                    int beforeDecimal = 2, afterDecimal = 2;

                    @Override
                    public CharSequence filter(CharSequence source, int start, int end,
                                               Spanned dest, int dstart, int dend) {
                        String temp = etCgpa.getText() + source.toString();

                        if (temp.equals(".")) {
                            return "0.";
                        } else if (temp.toString().indexOf(".") == -1) {
                            // no decimal point placed yet
                            if (temp.length() > beforeDecimal) {
                                return "";
                            }
                        } else {
                            temp = temp.substring(temp.indexOf(".") + 1);
                            if (temp.length() > afterDecimal) {
                                return "";
                            }
                        }

                        return super.filter(source, start, end, dest, dstart, dend);
                    }
                }
        });


        etEmail.setText(userSeekerDTOS.getData().getEmail());
        etName.setText(userSeekerDTOS.getData().getName());
        etMobile.setText(userSeekerDTOS.getData().getMno());



        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.cemra)
                .showImageForEmptyUri(R.drawable.cemra)
                .showImageOnFail(R.drawable.cemra)
                .cacheInMemory(true)
                .considerExifParams(true)
                .cacheOnDisk(true)
                .cacheOnDisc(true)
                .displayer(new SimpleBitmapDisplayer())
                .build();

        builder = new BottomSheet.Builder(getActivity()).sheet(R.menu.menu_cards);
        builder.title("Job Portal : Take Image From");
        builder.listener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {

                    case R.id.camera_cards:
                        if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
                            if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                try {
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                    File file = getOutputMediaFile(1);
                                    if (!file.exists()) {
                                        try {
                                            file.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                        //Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
                                        picUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", file);
                                    } else {
                                        picUri = Uri.fromFile(file); // create
                                    }

                                    prefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
                                    startActivityForResult(intent, PICK_FROM_CAMERA);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        }

                        break;
                    case R.id.gallery_cards:
                        if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
                            if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                                File file = getOutputMediaFile(1);
                                if (!file.exists()) {
                                    try {
                                        file.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                picUri = Uri.fromFile(file);

                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);

                            }
                        }
                        break;
                    case R.id.cancel_cards:
                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                dialog.dismiss();
                            }
                        });
                        break;
                }
            }
        });
        getData();

        IVimage.setOnClickListener(this);

        myp = new MonthYearPicker(getActivity());
        myp.build(
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (myp.getSelectedYear() != 0) {
                            etPassYear.setText("" + myp.getSelectedYear());

                        } else {
                            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.cant_futuer_date));
                        }
                    }
                }, null);


    }

    private void changeLanguage(View view) {
        modelLanguageDTO  =prefrence.getLanguage(AppConstans.LANGUAGE).getData();
        CustomTextview lgGender, lgEmail, lgYourName, lgMobile, lgCurrentAddress, lgPreferedLocation, lgJobType, lgQua, lgPassyear, lgCgpa, lgASOF, lgWorkExp, lgUploadResume,lgName;
        lgGender=(CustomTextview)view.findViewById(R.id.lgGender);
        lgEmail=(CustomTextview)view.findViewById(R.id.lgEmail);
        lgYourName=(CustomTextview)view.findViewById(R.id.lgYourName);
        lgMobile=(CustomTextview)view.findViewById(R.id.lgMobile);
        lgCurrentAddress=(CustomTextview)view.findViewById(R.id.lgCurrentAddress);
        lgPreferedLocation=(CustomTextview)view.findViewById(R.id.lgPreferedLocation);
        lgJobType=(CustomTextview)view.findViewById(R.id.lgJobType);
        lgQua=(CustomTextview)view.findViewById(R.id.lgQua);
        lgPassyear=(CustomTextview)view.findViewById(R.id.lgPassyear);
        lgCgpa=(CustomTextview)view.findViewById(R.id.lgCgpa);
        lgASOF=(CustomTextview)view.findViewById(R.id.lgASOF);
        lgWorkExp=(CustomTextview)view.findViewById(R.id.lgWorkExp);
        lgUploadResume=(CustomTextview)view.findViewById(R.id.lgUploadResume);


        lgGender.setText(modelLanguageDTO.getGender());
        lgEmail.setText(modelLanguageDTO.getEmail_login());
        lgYourName.setText(modelLanguageDTO.getUser_name());
        lgMobile.setText(modelLanguageDTO.getResister_mno());
        lgCurrentAddress.setText(modelLanguageDTO.getUser_address());
        lgPreferedLocation.setText(modelLanguageDTO.getUser_location());
        lgJobType.setText(modelLanguageDTO.getJob_type());
        lgQua.setText(modelLanguageDTO.getQua());
        lgPassyear.setText(modelLanguageDTO.getUser_passing_year());
        lgCgpa.setText(modelLanguageDTO.getUser_cgpa());
        lgASOF.setText(modelLanguageDTO.getJob_aofs());
        lgWorkExp.setText(modelLanguageDTO.getS_tool_tip1());
        lgUploadResume.setText(modelLanguageDTO.getUser_resume());

        RBmale.setText(modelLanguageDTO.getMale_keyword());
        RBfemale.setText(modelLanguageDTO.getFemale_keyword());
        seekerDashboardActivity.tvJobs.setText(modelLanguageDTO.getProfile_setting());

    }

    private void getData() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, AppConstans.BASE_URL + AppConstans.FETCH_ALL_CAT,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            generalDTO = new Gson().fromJson(response, FetchGeneralData.class);
                            showData();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("error", error.toString());
                    }
                }) {
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);

    }

    public void showData() {
        expList = generalDTO.getData().getExp();
        expList.add(0, new FetchGeneralData.Data.Exp(modelLanguageDTO.getS_tool_tip1()));
        exp_adapter = new ArrayAdapter<FetchGeneralData.Data.Exp>(getActivity(), android.R.layout.simple_spinner_dropdown_item, expList);
        exp_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpTotalExperienceYear.setAdapter(exp_adapter);

        locationsList = generalDTO.getData().getLocation();
        locationsList.add(0, new FetchGeneralData.Data.Location(modelLanguageDTO.getJ_location()));
        location_Adapter = new ArrayAdapter<FetchGeneralData.Data.Location>(getActivity(), android.R.layout.simple_spinner_dropdown_item, locationsList);
        location_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpPrefLoc.setAdapter(location_Adapter);


        // SpPrefLoc.setAdapter(location_Adapter);
        job_typesList = generalDTO.getData().getJob_type();
        job_typesList.add(0, new FetchGeneralData.Data.JobType(modelLanguageDTO.getJob_type()));
        job_type_Adapter = new ArrayAdapter<FetchGeneralData.Data.JobType>(getActivity(), android.R.layout.simple_spinner_dropdown_item, job_typesList);
        job_type_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpJobType.setAdapter(job_type_Adapter);


        qualificationsList = generalDTO.getData().getQualification();
        qualificationsList.add(0, new FetchGeneralData.Data.Qualification(modelLanguageDTO.getQua()));
        qualification_Adapter = new ArrayAdapter<FetchGeneralData.Data.Qualification>(getActivity(), android.R.layout.simple_spinner_dropdown_item, qualificationsList);
        qualification_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpQualification.setAdapter(qualification_Adapter);


        area_of_sectorsList = generalDTO.getData().getArea_of_s();
        area_of_sectorsList.add(0, new FetchGeneralData.Data.Area_of_s(modelLanguageDTO.getJob_aofs()));
        aos_Adapter = new ArrayAdapter<FetchGeneralData.Data.Area_of_s>(getActivity(), android.R.layout.simple_spinner_dropdown_item, area_of_sectorsList);
        aos_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpAreaOfSector.setAdapter(aos_Adapter);


        specializationList = generalDTO.getData().getSpecialization();
        specializationList.add(0, new FetchGeneralData.Data.Specialization(modelLanguageDTO.getSelect_sp()));
        specialization_Adapter = new ArrayAdapter<FetchGeneralData.Data.Specialization>(getActivity(), android.R.layout.simple_spinner_dropdown_item, specializationList);
        specialization_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpSpecialization.setAdapter(specialization_Adapter);



        job_by_roles_List = generalDTO.getData().getDesi();
        job_by_roles_List.add(0, new FetchGeneralData.Data.Desi(modelLanguageDTO.getDesi()));
        job_by_roles_Adapter = new ArrayAdapter<FetchGeneralData.Data.Desi>(getActivity(), android.R.layout.simple_spinner_dropdown_item, job_by_roles_List);
        job_by_roles_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        SpRoleType.setAdapter(job_by_roles_Adapter);
    }

    private void getSeekerInfo() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.SEEKER_INFO,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            final ModelSeekerLogin modelSeekerLogin = new Gson().fromJson(response, ModelSeekerLogin.class);

                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //Do something after 100ms
                                    viewSeekerProfile(modelSeekerLogin);
                                }
                            }, 700);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("error", error.toString());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.SEEKER_EMAIL, userSeekerDTOS.getData().getEmail());
                Log.e("value", params.toString());
                return params;
            }

        };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }


    public void viewSeekerProfile(ModelSeekerLogin userSeekerDTO) {

        // userSeekerDTO = prefrence.getUserDTO(Consts.SEEKER_DTO);
        resumeString=userSeekerDTO.getData().getResume();
        for (int i = 0; i < locationsList.size(); i++) {
            if (locationsList.get(i).getName().equalsIgnoreCase(userSeekerDTO.getData().getP_locaion())) {
                SpPrefLoc.setSelection(i);
                break;
            }
        }
        for (int i = 0; i < job_typesList.size(); i++) {
            if (job_typesList.get(i).getName().equalsIgnoreCase(userSeekerDTO.getData().getJob_type())) {
                SpJobType.setSelection(i);
                break;
            }
        }
        for (int i = 0; i < qualificationsList.size(); i++) {
            if (qualificationsList.get(i).getName().equalsIgnoreCase(userSeekerDTO.getData().getQua())) {
                SpQualification.setSelection(i);
                break;
            }
        }
        for (int i = 0; i < area_of_sectorsList.size(); i++) {
            if (area_of_sectorsList.get(i).getName().equalsIgnoreCase(userSeekerDTO.getData().getAofs())) {
                SpAreaOfSector.setSelection(i);
                break;
            }
        }
        for (int i = 0; i < expList.size(); i++) {
            if (expList.get(i).getName().equalsIgnoreCase(userSeekerDTO.getData().getExp())) {
                SpTotalExperienceYear.setSelection(i);
                break;
            }
        }

        tvUsername.setText(userSeekerDTO.getData().getName());
        etCurrentAddress.setText(userSeekerDTO.getData().getCurrent_address());
        etPassYear.setText(userSeekerDTO.getData().getP_year());
        etCgpa.setText(userSeekerDTO.getData().getCgpa());
        //  etCertification.setText(userSeekerDTO.getData().getCertification());
        etFileUpload.setText(userSeekerDTO.getData().getResume());
        String filenameArray[] = userSeekerDTO.getData().getResume().split("\\.");
        extensionResume = filenameArray[filenameArray.length - 1];
        Log.e("Resume", extensionResume);


        if (userSeekerDTO.getData().getGender().equalsIgnoreCase("Male")) {
            RBmale.setChecked(true);
            RBfemale.setChecked(false);
        } else if (userSeekerDTO.getData().getGender().equalsIgnoreCase("Female")) {
            RBfemale.setChecked(true);
            RBmale.setChecked(false);
        }



Log.e("Image",baseUrl+userSeekerDTO.getData().getImg());
        ImageLoader.getInstance().displayImage(baseUrl+userSeekerDTO.getData().getImg(), IVimage, options);
        if (userSeekerDTO.getData().getExp().equalsIgnoreCase("Fresher")) {

        } else if (userSeekerDTO.getData().getExp().equalsIgnoreCase("Experienced")) {


          /*  for (int i = 0; i < specializationList.size(); i++) {
                if (specializationList.get(i).getId().equalsIgnoreCase(userSeekerDTO.getData().get())) {
                    SpSpecialization.setSelection(i);
                    break;
                }
            }
            for (int i = 0; i < job_by_roles_List.size(); i++) {
                if (job_by_roles_List.get(i).getId().equalsIgnoreCase(userSeekerDTO.getData().get())) {
                    SpRoleType.setSelection(i);
                    break;
                }
            }*/

        }


    }

    public void Submit() {
        if (!Validate()) {
            return;
        } else {
            if (NetworkManager.isConnectToInternet(getActivity())) {
                uploadProfile();

            } else {
                ProjectUtils.showToast(getActivity(), getResources().getString(R.string.internet_connection));
            }

        }
    }

    public boolean Validate() {

        if (RGGender.getCheckedRadioButtonId() == -1) {
            Toast.makeText(getActivity(), getResources().getString(R.string.val_gen), Toast.LENGTH_SHORT).show();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etEmail)) {
            etEmail.setError(getResources().getString(R.string.val_email));
            etEmail.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etName)) {
            etName.setError(getResources().getString(R.string.val_name));
            etName.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etMobile)) {
            etMobile.setError(getResources().getString(R.string.val_phone));
            etMobile.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etCurrentAddress)) {
            etCurrentAddress.setError(getResources().getString(R.string.val_add));
            etCurrentAddress.requestFocus();
            return false;
        } else if (locationsList.get(SpPrefLoc.getSelectedItemPosition()).getName().equalsIgnoreCase(modelLanguageDTO.getJ_location())) {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_location));
            return false;
        } else if (job_typesList.get(SpJobType.getSelectedItemPosition()).getName().equalsIgnoreCase(modelLanguageDTO.getJob_type())) {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_job_type));
            return false;
        } else if (qualificationsList.get(SpQualification.getSelectedItemPosition()).getName().equalsIgnoreCase(modelLanguageDTO.getQua())) {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_qualification));
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etPassYear)) {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_pass_year));//
            etPassYear.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etCgpa)) {
            etCgpa.setError(getResources().getString(R.string.val_percent));
            etCgpa.requestFocus();
            return false;
        } else if (area_of_sectorsList.get(SpAreaOfSector.getSelectedItemPosition()).getName().equalsIgnoreCase(modelLanguageDTO.getJob_aofs())) {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_area));
            return false;
        }
       /* if (!validateResume()) {
            return false;
        }*/
        return true;
    }


    public boolean validateResume() {
        if (etFileUpload.getText().toString().trim().equalsIgnoreCase("0") && etFileUpload.getText().toString().trim().length() <= 0) {
            etFileUpload.setError(getResources().getString(R.string.val_upload_resume));
            etFileUpload.requestFocus();
            return false;
        } else {
            if (extensionResume.equalsIgnoreCase("pdf") || extensionResume.equalsIgnoreCase("doc") || extensionResume.equalsIgnoreCase("docx")) {
                etFileUpload.setError(null);
                etFileUpload.clearFocus();
                return true;//only true
            } else {
                etFileUpload.requestFocus();
                etFileUpload.setError(getResources().getString(R.string.val_upload_resume_a));
                return false;
            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnUpdate:
                Submit();
                break;
            case R.id.IVimage:
                builder.show();
                break;
            case R.id.etFileUpload:
                showFileChooser();
                 break;

            case R.id.etPassYear:
                myp.show();
               break;
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        ((TextView) adapterView.getChildAt(0)).setTypeface(font);
        ((TextView) adapterView.getChildAt(0)).setTextSize(14);

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    private File getOutputMediaFile(int type) {
        String root = Environment.getExternalStorageDirectory().toString();

        File mediaStorageDir = new File(root, Consts.JOB_PORTAL);

        /**Create the storage directory if it does not exist*/
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        /**Create a media file name*/
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == 1) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    Consts.JOB_PORTAL + timeStamp + ".png");

        } else {
            return null;
        }

        return mediaFile;
    }

    private File getOutputMediaFile1(int type) {
        String root = Environment.getExternalStorageDirectory().toString();

        File mediaStorageDir = new File(root, Consts.JOB_PORTAL);
        /**Create the storage directory if it does not exist*/
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        /**Create a media file name*/
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == 1) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    Consts.JOB_PORTAL + timeStamp + ".pdf");

        } else {
            return null;
        }

        return mediaFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK) {
            try {
                filePath = data.getData();
                Log.e("front tempUri", "" + filePath);
                if (filePath != null) {

                    Log.e("PDFFILEZILA", "" + filePath);
                    pathOfResume = filePath.getPath();
                    Log.e("PDF PATH OF FILE", "" + pathOfResume);

                    //     resume = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), filePath));
                    pathOfResume = pathOfResume.substring(pathOfResume.indexOf('/', 1));
                    etFileUpload.setText(pathOfResume);
                    // Log.e("PDF PATH ", "" + resume);

                    String filenameArray[] = String.valueOf(resume).split("\\.");
                    extensionResume = filenameArray[filenameArray.length - 1];
                    Log.e("extensionResume", "" + extensionResume);
                } else {
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        if (requestCode == CROP_CAMERA_IMAGE) {

            if (data != null) {
                picUri = Uri.parse(data.getExtras().getString("resultUri"));
                try {
                    //bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
                    pathOfImage = picUri.getPath();
                    imageCompression = new ImageCompression(getActivity());
                    imageCompression.execute(pathOfImage);
                    imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
                        @Override
                        public void processFinish(String imagePath) {
                            updateUserImage(IVimage, "file://" + imagePath);
                            image = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), Uri.parse("file://" + imagePath)));
                            String filenameArray[] = imagePath.split("\\.");
                            extensionIMG = filenameArray[filenameArray.length - 1];
                            Log.e("MY image", image + "");
                            try {
                                // bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), resultUri);
                                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                                bm = BitmapFactory.decodeFile(imagePath, bmOptions);
                                ByteArrayOutputStream buffer = new ByteArrayOutputStream(bm.getWidth() * bm.getHeight());
                                bm.compress(Bitmap.CompressFormat.PNG, 100, buffer);
                                //resultByteArray = buffer.toByteArray();
                                bm.recycle();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        if (requestCode == CROP_GALLERY_IMAGE) {

            if (data != null) {
                picUri = Uri.parse(data.getExtras().getString("resultUri"));
                Log.e("image 1", picUri + "");
                try {
                    bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), picUri);
                    pathOfImage = picUri.getPath();
                    imageCompression = new ImageCompression(getActivity());
                    imageCompression.execute(pathOfImage);
                    imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
                        @Override
                        public void processFinish(String imagePath) {
                            updateUserImage(IVimage, "file://" + imagePath);
                            image = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), Uri.parse("file://" + imagePath)));
                            Log.e("image 2", imagePath);
                            Log.e("MY image", image + "");
                            String filenameArray[] = imagePath.split("\\.");
                            extensionIMG = filenameArray[filenameArray.length - 1];
                            try {
                                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                                bm = BitmapFactory.decodeFile(imagePath, bmOptions);
                                ByteArrayOutputStream buffer = new ByteArrayOutputStream(bm.getWidth() * bm.getHeight());
                                bm.compress(Bitmap.CompressFormat.PNG, 100, buffer);
                                // resultByteArray = buffer.toByteArray();

                                bm.recycle();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        if (requestCode == PICK_FROM_CAMERA && resultCode == RESULT_OK) {
            if (picUri != null) {

                picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
                // image = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), picUri));
                startCropping(picUri, CROP_CAMERA_IMAGE);
            } else {
                picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
                // image = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), picUri));

                startCropping(picUri, CROP_CAMERA_IMAGE);
            }
        }


        if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
            try {
                Uri tempUri = data.getData();

                Log.e("front tempUri", "" + tempUri);
                if (tempUri != null) {
                    //    image = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), tempUri));
                    Log.e("image 2", image + "");
                    startCropping(tempUri, CROP_GALLERY_IMAGE);
                } else {

                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

    }

    public void startCropping(Uri uri, int requestCode) {

        Intent intent = new Intent(getActivity(), MainFragment.class);
        intent.putExtra("imageUri", uri.toString());
        intent.putExtra("requestCode", requestCode);
        startActivityForResult(intent, requestCode);
    }

    public void updateUserImage(final ImageView imageView, String uri) {
        ImageLoader.getInstance().displayImage(uri, imageView, options, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                IVimage.setImageResource(R.drawable.cemra);

            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                updateSeekerProfile();
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                IVimage.setImageResource(R.drawable.cemra);
            }
        });
    }

    private void showFileChooser() {
        if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_PDF_REQUEST, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            File file = getOutputMediaFile1(1);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            picUri = Uri.fromFile(file);

            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("application/pdf");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);

        } else {
            ProjectUtils.showToast(getActivity(), "Permission is not Granted");
        }


    }


    private static byte[] convertPDFToByteArray(String str) {

        InputStream inputStream = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {

            inputStream = new FileInputStream(str);

            byte[] buffer = new byte[1024];
            baos = new ByteArrayOutputStream();

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return baos.toByteArray();
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        seekerDashboardActivity = (SeekerDashboardActivity) activity;
    }

/*
    public byte[] getImageByte() {
        try {
            Bitmap bitmap = ((BitmapDrawable) IVimage.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            resultByteArray = baos.toByteArray();
        } catch (Exception e) {
            //   System.err.printf("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
            e.printStackTrace();
            // Perform any other exception handling that's appropriate.
        }
        return resultByteArray;
    }
*/

    public void uploadProfile() {
        /*  .addMultipartFile(getFileParms()) */
        if (resumeString.equalsIgnoreCase(etFileUpload.getText().toString())) {
            ProjectUtils.showProgressDialog(getActivity(), true, "Please wait...");
            AndroidNetworking.upload(AppConstans.BASE_URL + AppConstans.USER_PROFILE_UPDATE)
                    .addMultipartParameter(getParms())

                    .setTag("uploadTest")
                    .setPriority(Priority.IMMEDIATE)
                    .build()
                    .setUploadProgressListener(new UploadProgressListener() {
                        @Override
                        public void onProgress(long bytesUploaded, long totalBytes) {
                            Log.e("Byte", bytesUploaded + "  !!! " + totalBytes);
                        }
                    })
                    .getAsString(new StringRequestListener() {
                        @Override
                        public void onResponse(String response) {
                            ProjectUtils.pauseProgressDialog();
                            Log.e("POST", response.toString());
                            try {
                                JSONObject jObj = new JSONObject(response);
                                userSeekerDTOS = new Gson().fromJson(jObj.toString(), ModelSeekerLogin.class);
                                prefrence.setUserDTO(userSeekerDTOS, AppConstans.SEEKERDTO);
                                if (userSeekerDTOS.getStaus().equalsIgnoreCase("true")) {
                                    ProjectUtils.showToast(getActivity(), userSeekerDTOS.getMessage());
                                    //   prefrence.setUserDTO(userSeekerDTO, Consts.SEEKER_DTO);
                                } else {
                                    ProjectUtils.showToast(getActivity(), userSeekerDTOS.getMessage());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }

                        @Override
                        public void onError(ANError anError) {
                            ProjectUtils.pauseProgressDialog();
                            Log.e(TAG, "error : " + anError.getErrorBody() + " " + anError.getResponse() + " " + anError.getErrorDetail() + " " + anError.getMessage());

                        }
                    });
        } else {
            String filenameArray[] = etFileUpload.getText().toString().split("\\.");
            String extension = filenameArray[filenameArray.length-1];
if (extension.equalsIgnoreCase("pdf")){
            ProjectUtils.showProgressDialog(getActivity(), true, "Please wait...");
            AndroidNetworking.upload(AppConstans.BASE_URL + AppConstans.USER_PROFILE_UPDATE)
                    .addMultipartParameter(getParms())
                    .addMultipartFile("resume", new File(pathOfResume))
                    .setTag("uploadTest")
                    .setPriority(Priority.IMMEDIATE)
                    .build()
                    .setUploadProgressListener(new UploadProgressListener() {
                        @Override
                        public void onProgress(long bytesUploaded, long totalBytes) {
                            Log.e("Byte", bytesUploaded + "  !!! " + totalBytes);
                        }
                    })
                    .getAsString(new StringRequestListener() {
                        @Override
                        public void onResponse(String response) {
                            ProjectUtils.pauseProgressDialog();
                            Log.e("POST", response.toString());
                            try {
                                JSONObject jObj = new JSONObject(response);


                                userSeekerDTOS = new Gson().fromJson(jObj.toString(), ModelSeekerLogin.class);
                                prefrence.setUserDTO(userSeekerDTOS, AppConstans.SEEKERDTO);

                                if (userSeekerDTOS.getStaus().equalsIgnoreCase("true")) {
                                    ProjectUtils.showToast(getActivity(), userSeekerDTOS.getMessage());
                                    //   prefrence.setUserDTO(userSeekerDTO, Consts.SEEKER_DTO);
                                } else {
                                    ProjectUtils.showToast(getActivity(), userSeekerDTOS.getMessage());
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        @Override
                        public void onError(ANError anError) {
                            ProjectUtils.pauseProgressDialog();
                            Log.e(TAG, "error : " + anError.getErrorBody() + " " + anError.getResponse() + " " + anError.getErrorDetail() + " " + anError.getMessage());
                        }
                    });
        }else {
    etFileUpload.setText("");
    ProjectUtils.showToast(getActivity(),"Try with pdf file");
}
    }

    }
    public Map<String, File> getFileParms() {
        HashMap<String, File> valuesFile = new HashMap<>();
      /*  if (image != null) {
            valuesFile.put(Consts.AVTAR, image);
        }
        if (resume != null) {
            valuesFile.put(Consts.RESUME, resume);
        }*/
        valuesFile.put(AppConstans.IMG, image);

        Log.e("UPDATE_PROFILE_FILE", valuesFile.toString());
        return valuesFile;
    }

    public ConcurrentHashMap<String, String> getParms() {

        ConcurrentHashMap<String, String> values = new ConcurrentHashMap<String, String>();
        values.put(AppConstans.EMAIL, userSeekerDTOS.getData().getEmail());
        if (RBmale.isChecked()) {
            values.put(AppConstans.GENDER, "Male");
            Log.e("MALE", "MALE");

        } else if (RBfemale.isChecked()) {
            values.put(AppConstans.GENDER, "Female");
            Log.e("FEMALE", "FEMALE");
        }
        values.put(AppConstans.CURRENT_ADDRESS, ProjectUtils.getEditTextValue(etCurrentAddress));
        values.put(AppConstans.P_LOCAION, locationsList.get(SpPrefLoc.getSelectedItemPosition()).getName() + "");
        values.put(AppConstans.JOB_TYPE, job_typesList.get(SpJobType.getSelectedItemPosition()).getName() + "");
        values.put(AppConstans.QUA, qualificationsList.get(SpQualification.getSelectedItemPosition()).getName() + "");
        values.put(AppConstans.CGPA, ProjectUtils.getEditTextValue(etCgpa));
        values.put(AppConstans.P_YEAR, ProjectUtils.getEditTextValue(etPassYear));
        values.put(AppConstans.AOFS, area_of_sectorsList.get(SpAreaOfSector.getSelectedItemPosition()).getName() + "");
        values.put(AppConstans.COUNTER, "1");
        values.put(AppConstans.MOBILE_NO, etMobile.getText().toString());
        values.put(AppConstans.NAME, etName.getText().toString());
            values.put(AppConstans.EXPERIENCE, expList.get(SpTotalExperienceYear.getSelectedItemPosition()).getName() + "");



        Log.e("UPDATE_PROFILE", values.toString());
        return values;
    }

    private void updateSeekerProfile() {
        AndroidNetworking.upload(AppConstans.BASE_URL + AppConstans.PRO_PIC_UPLOAD)
                .addMultipartParameter(AppConstans.S_EMAIL, userSeekerDTOS.getData().getEmail())
                .addMultipartFile(getFileParms())
                .setTag("uploadTest")
                .setPriority(Priority.IMMEDIATE)
                .build()
                .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                        Log.e("Byte", bytesUploaded + "  !!! " + totalBytes);
                    }
                })
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();
                        Log.e("POST", response.toString());
                        try {
                            JSONObject jObj = new JSONObject(response);
                            if (jObj.getString("staus").equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(getActivity(), jObj.getString("message"));
                            }


/* ProjectUtils.showToast(getActivity(), userSeekerDTO.getMessage());
 {"staus":"true","":"Profile pic update","data":""}

                            if (userSeekerDTO.getStaus().equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(getActivity(), userSeekerDTO.getMessage());
                                //   prefrence.setUserDTO(userSeekerDTO, Consts.SEEKER_DTO);
                            } else {
                                ProjectUtils.showToast(getActivity(), userSeekerDTO.getMessage());
                            }*/
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(ANError anError) {
                        ProjectUtils.pauseProgressDialog();
                        Log.e(TAG, "error : " + anError.getErrorBody() + " " + anError.getResponse() + " " + anError.getErrorDetail() + " " + anError.getMessage());

                    }
                });
    }

    public void Search_Dir(File dir) {

        String pdfPattern = ".pdf";

        File FileList[] = dir.listFiles();

        if (FileList != null) {
            for (int i = 0; i < FileList.length; i++) {

                if (FileList[i].isDirectory()) {
                    Search_Dir(FileList[i]);
                } else {
                    if (FileList[i].getName().endsWith(pdfPattern)) {
                        //here you have that file.

                    }
                }
            }
        }

    }

    public void showDialog(Activity activity, String msg) {
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.pdf_pic_dialog);

        ListView mListView;
        mListView = (ListView) dialog.findViewById(R.id.listAttachments);
        fileList = new ArrayList<File>();
        fileListString = new ArrayList<String>();
        Search_Dir(Environment.getExternalStorageDirectory());
        ArrayAdapter arrayAdapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, fileListString);
        mListView.setAdapter(arrayAdapter);
        //  TextView text = (TextView) dialog.findViewById(R.id.text_dialog);
        //  text.setText(msg);

        //   Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
             /*   dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
    */
        dialog.show();

    }


}
