package com.pixelnx.sam.jobportal.Fragment;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
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.RecruiterDashboardActivity;
import com.pixelnx.sam.jobportal.DTO.BaseDTO;
import com.pixelnx.sam.jobportal.DTO.UserRecruiterDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelLanguageDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelRecruiterInfo;
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.CustomTextviewBold;
import com.pixelnx.sam.jobportal.utils.ImageCompression;
import com.pixelnx.sam.jobportal.utils.MainFragment;
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.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;
import static com.android.volley.VolleyLog.TAG;


public class RecruiterUpdateProfileFragment extends Fragment implements View.OnClickListener {

    private CircleImageView ivLogoOrg;
    private RadioGroup rgTypeRec;
    private RadioButton rbCompany, rbConsultant;
    private CustomEdittext etOrgLoc, etOrgAddress, etOrgWebsite, etOrgDescription, etName;
    private CustomButton btnUpdate;
    private CustomTextviewBold planDetails;
    RecruiterDashboardActivity recruiterDashboardActivity;
    private CustomTextSubHeader tvUsername;
    private SharedPrefrence prefrence;
    ModelSeekerLogin userRecruiterDTO;
    UploadFileToServer uploadFileToServer;
    File fileNew;
    View view;
    private ModelLanguageDTO.Data data;
    private String errorMSG = "";
    private DisplayImageOptions options;
    Uri picUri;
    int PICK_FROM_CAMERA = 1, PICK_FROM_GALLERY = 2;
    int CROP_CAMERA_IMAGE = 3, CROP_GALLERY_IMAGE = 4;

    BottomSheet.Builder builder;
    String pathOfImage, extensionIMG;
    Bitmap bm;
    ImageCompression imageCompression;
    byte[] resultByteArray;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_update_profile_recruiter, container, false);
        ProjectUtils.initImageLoader(getActivity());

        prefrence = SharedPrefrence.getInstance(getActivity());
        userRecruiterDTO = prefrence.getUserDTO(AppConstans.SEEKERDTO);
        data = prefrence.getLanguage(AppConstans.LANGUAGE).getData();
        try {
            errorMSG = data.getAll_field_required();
        } catch (Exception e) {
            e.printStackTrace();
        }
        recruiterDashboardActivity.search_icon.setVisibility(View.INVISIBLE);
        recruiterDashboardActivity.filter_icon.setVisibility(View.INVISIBLE);
        init(view);
        return view;
    }

    private void init(View view) {
        tvUsername = (CustomTextSubHeader) view.findViewById(R.id.tvUsername);
        ivLogoOrg = (CircleImageView) view.findViewById(R.id.ivLogoOrg);
        etOrgLoc = (CustomEdittext) view.findViewById(R.id.etOrgLoc);
        etOrgAddress = (CustomEdittext) view.findViewById(R.id.etOrgAddress);
        etOrgWebsite = (CustomEdittext) view.findViewById(R.id.etOrgWebsite);
        etOrgDescription = (CustomEdittext) view.findViewById(R.id.etOrgDescription);
        planDetails = (CustomTextviewBold) view.findViewById(R.id.planDetails);
        etName = (CustomEdittext) view.findViewById(R.id.etName);

        rgTypeRec = (RadioGroup) view.findViewById(R.id.rgTypeRec);
        rbCompany = (RadioButton) view.findViewById(R.id.rbCompany);
        rbConsultant = (RadioButton) view.findViewById(R.id.rbConsultant);

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

        changeLanguage(view);

        btnUpdate.setOnClickListener(this);

        rbCompany.setOnClickListener(this);
        rbConsultant.setOnClickListener(this);

        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;
                }
            }
        });
        ivLogoOrg.setOnClickListener(this);
        viewRecruiterProfile();


    }

    private void viewRecruiterProfile() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.RECRUITER_INFO,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(final String response) {
                        try {
                            final ModelRecruiterInfo info = new Gson().fromJson(response, ModelRecruiterInfo.class);
                            final Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //Do something after 100ms
                                    Log.e("RESO", response);
                                    try {
                                        viewProfile(info);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, 400);
                        } 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.RE_EMAIL, userRecruiterDTO.getData().getEmail());
                Log.e("value", params.toString());
                return params;
            }

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


    }

    private void changeLanguage(View view) {
        CustomTextview lgLoc, lgType, lgAddress, lgWebsite, lgDes, lgName;
        lgLoc = (CustomTextview) view.findViewById(R.id.lgLoc);
        lgType = (CustomTextview) view.findViewById(R.id.lgType);
        lgAddress = (CustomTextview) view.findViewById(R.id.lgAddress);
        lgWebsite = (CustomTextview) view.findViewById(R.id.lgWebsite);
        lgDes = (CustomTextview) view.findViewById(R.id.lgDes);
        lgName = (CustomTextview) view.findViewById(R.id.lgName);

        try {
            recruiterDashboardActivity.tvJobs.setText(data.getR_profile_setting());
            lgLoc.setText("" + data.getOrg_location11());
            lgWebsite.setText("" + data.getOrg_website());
            lgType.setText("" + data.getOrg_type());
            lgAddress.setText("" + data.getOrg_address1());
            lgDes.setText("" + data.getOrg_desc());
            rbCompany.setText("" + data.getType1());
            rbConsultant.setText("" + data.getType2());
            planDetails.setText("" + data.getPlan());
            lgName.setText("" + data.getValidation_org_name());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void viewProfile(ModelRecruiterInfo modelSeekerLogin) throws Exception {
        tvUsername.setText("" + modelSeekerLogin.getData().getName());
        etName.setText("" + modelSeekerLogin.getData().getName());
        etOrgLoc.setText(modelSeekerLogin.getData().getLocation());
        etOrgAddress.setText(modelSeekerLogin.getData().getAddress());
        etOrgWebsite.setText(modelSeekerLogin.getData().getWebsite());
        etOrgDescription.setText(modelSeekerLogin.getData().getDes());

        ImageLoader.getInstance().displayImage(userRecruiterDTO.getBase_url() + modelSeekerLogin.getData().getImg(), ivLogoOrg, options);
        if (modelSeekerLogin.getData().getOrg_type().equalsIgnoreCase("consultancy")) {
            rbConsultant.setChecked(true);
            rbCompany.setChecked(false);
        } else if (modelSeekerLogin.getData().getOrg_type().equalsIgnoreCase("company")) {
            rbCompany.setChecked(true);
            rbConsultant.setChecked(false);
        }
        planDetails.setText(data.getPlan() + "  " + modelSeekerLogin.getData().getPlan() + "\n" + data.getPay_date() + "  " + modelSeekerLogin.getData().getPay_date() + ", " + modelSeekerLogin.getData().getMonth() + " Month");
    }

    public void submitForm() {
        if (!SelectType()) {
            return;
        } else if (!Validate()) {
            return;
        } else {
            check();
        }
    }


    public boolean SelectType() {

        if (rgTypeRec.getCheckedRadioButtonId() == -1) {
            Toast.makeText(getActivity(), errorMSG, Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }
    }

    public boolean Validate() {
        if (!ProjectUtils.IsEditTextValidation(etOrgLoc)) {
            etOrgLoc.setError(errorMSG);
            etOrgLoc.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etOrgAddress)) {
            etOrgAddress.setError(errorMSG);
            etOrgAddress.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etOrgWebsite)) {
            etOrgWebsite.setError(errorMSG);
            etOrgWebsite.requestFocus();
            return false;
        } else if (!ProjectUtils.IsEditTextValidation(etOrgDescription)) {
            etOrgDescription.setError(errorMSG);
            etOrgDescription.requestFocus();
            return false;
        }


        return true;
    }

    public void check() {
        if (rbCompany.isChecked() || rbConsultant.isChecked()) {
            if (NetworkManager.isConnectToInternet(getActivity())) {
                UpdateProfile();
            } else {
                ProjectUtils.showToast(getActivity(), getResources().getString(R.string.internet_connection));
            }
        } else {
            ProjectUtils.showToast(getActivity(), getResources().getString(R.string.val_com_con));
        }
    }


    public void UpdateProfile() {

        ProjectUtils.showProgressDialog(getActivity(), false, "Please Wait");
        String ty = "";
        if (rbCompany.isChecked()) {
            ty = "company";
        }
        if (rbConsultant.isChecked()) {
            ty = "consultancy";

        }

        AndroidNetworking.upload(AppConstans.BASE_URL + AppConstans.RECRUITER_PROFILE_UPDATE)
                .addMultipartParameter(AppConstans.EMAIL, userRecruiterDTO.getData().getEmail())
                .addMultipartParameter(AppConstans.ORG_TYPE, ty)
                .addMultipartParameter(AppConstans.LOCATION, ProjectUtils.getEditTextValue(etOrgLoc))
                .addMultipartParameter(AppConstans.ADDRESS, ProjectUtils.getEditTextValue(etOrgAddress))
                .addMultipartParameter(AppConstans.WEBSITE, ProjectUtils.getEditTextValue(etOrgWebsite))
                .addMultipartParameter(AppConstans.DISCRIPTION, ProjectUtils.getEditTextValue(etOrgDescription))
                .addMultipartParameter(AppConstans.NAME, ProjectUtils.getEditTextValue(etName))
                .addMultipartFile(AppConstans.IMG, fileNew)
                .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);
                            String staus = jObj.getString("staus");

                            String msg = jObj.getString("message");
                            if (staus.equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(getActivity(), msg);
                                //getUserDetails();
                            } else {
                                ProjectUtils.showToast(getActivity(), msg);
                            }
                        } 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());
                    }
                });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnUpdate:
                submitForm();
                break;
            case R.id.ivLogoOrg:
                builder.show();
                break;
        }
    }


    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;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CROP_CAMERA_IMAGE) {
            if (data != null) {
                picUri = Uri.parse(data.getExtras().getString("resultUri"));
                try {
                    //bitmap = MediaStore.Images.Media.getBitmap(EditProfile.this.getContentResolver(), resultUri);

                    pathOfImage = picUri.getPath();

                    fileNew = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), picUri));
                    imageCompression = new ImageCompression(getActivity());
                    imageCompression.execute(pathOfImage);
                    imageCompression.setOnTaskFinishedEvent(new ImageCompression.AsyncResponse() {
                        @Override
                        public void processFinish(String imagePath) {
                            updateUserImage(ivLogoOrg, "file://" + imagePath);
                            fileNew = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), Uri.parse("file://" + imagePath)));
                            String filenameArray[] = imagePath.split("\\.");
                            extensionIMG = filenameArray[filenameArray.length - 1];

                            //   fileNew="file://"+imagePath;
                            //         fileNew = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), Uri.parse(imagePath)));
                            Log.e("image", "file://" + imagePath + "  ppp   " + fileNew);
                            try {
                                // bitmap = MediaStore.Images.Media.getBitmap(EditProfile.this.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"));
                fileNew = new File(ConvertUriToFilePath.getPathFromURI(getActivity(), 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(ivLogoOrg, "file://" + imagePath);
                            String filenameArray[] = imagePath.split("\\.");
                            extensionIMG = filenameArray[filenameArray.length - 1];
                            // fileNew=ConvertUriToFilePath.getPathFromURI(getActivity(), Uri.parse(imagePath));

                            Log.e("image2", "file://" + imagePath + "  ppp   " + picUri);

                            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));
                startCropping(picUri, CROP_CAMERA_IMAGE);
            } else {
                picUri = Uri.parse(prefrence.getValue(Consts.IMAGE_URI_CAMERA));
                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) {
                    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) {
                ivLogoOrg.setImageResource(R.drawable.cemra);
            }

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

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        recruiterDashboardActivity = (RecruiterDashboardActivity) activity;

    }
}
