package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.pickimage.bean.PickResult;
import com.cygnusa.hyperm.pickimage.bundle.PickSetup;
import com.cygnusa.hyperm.pickimage.dialog.PickImageDialog;
import com.cygnusa.hyperm.pickimage.listeners.IPickCancel;
import com.cygnusa.hyperm.pickimage.listeners.IPickResult;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.widget.SubtitleCollapsingToolbarLayout;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.UserResponse;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyProfileActivity extends AppCompatActivity implements IPickResult {
    public Calendar calendar;
    public Calendar calendarret;
    public TextInputLayout editInputDob, editInputEmail, editInputWedding, getEditInputMobile;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    AppBarLayout appBarLayout;
    Toolbar toolbar;
    ImageView userImage;
    FloatingActionButton editButton;
    FloatingActionButton cameraButton;
    LinearLayout bottomLayout;
    EditText firstName, lastName, dob, email, mobile, doj, dealer, zone, state, city, region, designation, weddingDate;
    Button submitButton;
    UserResponse MY_PROFILE = new UserResponse();
    SubtitleCollapsingToolbarLayout collapsingToolbar;
    String IMAGE_PATH = "";
    ImageButton toolEditIcon, helpIcon;
    CheckBox checkBoxMarried;
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog alertDialog;
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
    boolean isDOB = false;
    private ImageView dobCalendar, weddingCalendar;
    private int year;
    private int month;
    private int day;
    public DatePickerDialog.OnDateSetListener tolistener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int y, int monthOfYear, int dayOfMonth) {
            year = y;
            month = monthOfYear;
            day = dayOfMonth;
            String datevalue = String.valueOf(day);
            int mval = (month + 1);
            String monthvalue = String.valueOf(mval);
            String date = "0";
            String monthname = "0";
            if (datevalue.length() == 1) {
                date = "0" + datevalue;
            } else {
                date = datevalue;
            }

            if (monthvalue.length() == 1) {
                monthname = "0" + monthvalue;
            } else {
                monthname = monthvalue;
            }
            //dateValue = String.valueOf(year) + "-" + (month + 1) + "-" + day + " ";
            String dateValue = String.valueOf(year) + "-" + monthname + "-" + date;
            dob.setText(dateFormate(dateValue));
            if (isDOB) {
                dob.setText(dateFormate(dateValue));
            } else {
                weddingDate.setText(dateFormate(dateValue));
            }
        }
    };
    private LinearLayout linearWeddingDate;
    private boolean isEditable = false;

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private static String displayMonth(String date) throws ParseException {
        Date d = new SimpleDateFormat("dd-MM-yyyy").parse(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        String monthName = new SimpleDateFormat("dd-MMM-yyyy").format(cal.getTime());
        return monthName;
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_profile);
        setupWindowAnimations();
        setupUI(findViewById(R.id.main_content));
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
        restService = ((MainApplication) getApplication()).getClient();
        appBarLayout = findViewById(R.id.appBarLayout);
        userImage = findViewById(R.id.userImage);
        toolbar = findViewById(R.id.toolbar);
        bottomLayout = findViewById(R.id.bottomLayout);
        toolEditIcon = findViewById(R.id.toolEditIcon);
        helpIcon = findViewById(R.id.helpIcon);
        helpIcon.setVisibility(View.VISIBLE);
        email = findViewById(R.id.email);
        editInputEmail = findViewById(R.id.txtemail);
        editInputDob = findViewById(R.id.txtInputDob);
        editInputWedding = findViewById(R.id.txtInputWedding);
        editInputWedding = findViewById(R.id.edit_mobile);


        mobile = findViewById(R.id.mobile);
        doj = findViewById(R.id.doj);
        dob = findViewById(R.id.dob);
        dealer = findViewById(R.id.dealer);
        zone = findViewById(R.id.zone);
        region = findViewById(R.id.region);
        state = findViewById(R.id.state);
        city = findViewById(R.id.city);
        designation = findViewById(R.id.designation);
        checkBoxMarried = findViewById(R.id.checkMarried);
        weddingDate = findViewById(R.id.weddingDate);
        dobCalendar = findViewById(R.id.dob_date);
        weddingCalendar = findViewById(R.id.weddding_date);
        linearWeddingDate = findViewById(R.id.linear_wedding_date);

        submitButton = findViewById(R.id.submitButton);
        email.setEnabled(false);
        weddingDate.setEnabled(false);
        dob.setEnabled(false);
        doj.setEnabled(false);
        dealer.setEnabled(false);
        designation.setEnabled(false);
        mobile.setEnabled(false);
        region.setEnabled(false);
        state.setEnabled(false);
        zone.setEnabled(false);
        city.setEnabled(false);
        weddingCalendar.setVisibility(View.VISIBLE);
        checkBoxMarried.setChecked(false);


        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


        collapsingToolbar = findViewById(R.id.collapsing_toolbar);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (Math.abs(verticalOffset) - appBarLayout.getTotalScrollRange() == 0) {
                    toolbar.setBackgroundColor(getResources().getColor(R.color.bg_color));
                    toolEditIcon.setVisibility(View.VISIBLE);
                    helpIcon.setVisibility(View.GONE);
                } else {
                    toolbar.setBackgroundColor(Color.TRANSPARENT);
                    toolEditIcon.setVisibility(View.GONE);
                    helpIcon.setVisibility(View.VISIBLE);
                }
            }
        });

        toolEditIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editButton.performClick();
            }
        });
        dobCalendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDOB = true;
                Calendar c = Calendar.getInstance();
                c.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 18);
                Date date = new Date();

                if (dob.getText().toString().trim().isEmpty()
                        || dob.getText().toString().trim().equalsIgnoreCase("0000-00-00")
                        || dob.getText().toString().trim().equalsIgnoreCase("00-00-0000")
                        || dob.getText().toString().trim().equalsIgnoreCase("00/00/0000")
                        || dob.getText().toString().trim().equalsIgnoreCase("0000/00/00")) {
                    date = c.getTime();
                } else {
                    if (dob.getText().toString().trim().contains("-")) {
                        try {
                            date = new SimpleDateFormat("yyyy-MM-dd").parse(dob.getText().toString().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            date = new SimpleDateFormat("dd-MMM-yyyy").parse(dob.getText().toString().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                c.setTime(date);

                DatePickerDialog dialog = new DatePickerDialog(MyProfileActivity.this, tolistener,
                        c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                try {
                    c = Calendar.getInstance();
                    c.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 18);
                    DatePicker datePicker = dialog.getDatePicker();
                    datePicker.setMaxDate(c.getTime().getTime());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.show();
            }
        });


        weddingCalendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDOB = false;
                Calendar c = Calendar.getInstance();
                Date date = new Date();

                if (weddingDate.getText().toString().trim().isEmpty()
                        || weddingDate.getText().toString().trim().equalsIgnoreCase("0000-00-00")
                        || weddingDate.getText().toString().trim().equalsIgnoreCase("00-00-0000")
                        || weddingDate.getText().toString().trim().equalsIgnoreCase("00/00/0000")
                        || weddingDate.getText().toString().trim().equalsIgnoreCase("0000/00/00")) {
                    date = c.getTime();
                } else {
                    if (weddingDate.getText().toString().trim().contains("-")) {
                        try {
                            date = new SimpleDateFormat("yyyy-MM-dd").parse(weddingDate.getText().toString().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            date = new SimpleDateFormat("dd-MMM-yyyy").parse(weddingDate.getText().toString().trim());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
                c.setTime(date);

                DatePickerDialog dialog = new DatePickerDialog(MyProfileActivity.this, tolistener,
                        c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                try {
                    DatePicker datePicker = dialog.getDatePicker();
                    datePicker.setMaxDate(c.getTime().getTime());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dialog.show();
            }
        });


        editButton = findViewById(R.id.editButton);
        cameraButton = findViewById(R.id.cameraButton);
        cameraButton.hide();
        bottomLayout.setVisibility(View.INVISIBLE);
        linearWeddingDate.setVisibility(View.GONE);
        dobCalendar.setVisibility(View.INVISIBLE);
        checkBoxMarried.setEnabled(false);
        weddingCalendar.setVisibility(View.INVISIBLE);
        getMyProfile();

        checkBoxMarried.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = ((CheckBox) v).isChecked();
                if (checked) {
                    linearWeddingDate.setVisibility(View.GONE);
                    if (!isEditable) {
                        weddingCalendar.setVisibility(View.INVISIBLE);
                    } else {
                        weddingCalendar.setVisibility(View.VISIBLE);
                    }
                } else {
                    linearWeddingDate.setVisibility(View.GONE);
                    if (!isEditable) {
                        weddingCalendar.setVisibility(View.INVISIBLE);
                    } else {
                        weddingCalendar.setVisibility(View.VISIBLE);
                    }
                }
            }
        });


        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cameraButton.getVisibility() == View.GONE) {
                    IMAGE_PATH = "";
                    setUpperHintColor(getResources().getColor(R.color.bg_color_dark), editInputDob);
                    setUpperHintColor(getResources().getColor(R.color.bg_color_dark), editInputEmail);
                    setUpperHintColor(getResources().getColor(R.color.bg_color_dark), editInputWedding);

                    mobile.setTextColor(getResources().getColor(R.color.material_grey300));
                    designation.setTextColor(getResources().getColor(R.color.material_grey300));
                    dealer.setTextColor(getResources().getColor(R.color.material_grey300));
                    doj.setTextColor(getResources().getColor(R.color.material_grey300));
                    zone.setTextColor(getResources().getColor(R.color.material_grey300));
                    region.setTextColor(getResources().getColor(R.color.material_grey300));
                    state.setTextColor(getResources().getColor(R.color.material_grey300));
                    city.setTextColor(getResources().getColor(R.color.material_grey300));
                    weddingDate.setHintTextColor(getResources().getColor(R.color.material_grey700));
                    cameraButton.show();
                    cameraButton.startAnimation(AnimationUtils.loadAnimation(MyProfileActivity.this, R.anim.zoomin));
                    slideToTop(bottomLayout);
                    email.setEnabled(true);
                    checkBoxMarried.setEnabled(true);
                    dobCalendar.setVisibility(View.VISIBLE);
                    isEditable = true;

                } else {

                    setUpperHintColor(getResources().getColor(R.color.btn_bg_color), editInputDob);
                    setUpperHintColor(getResources().getColor(R.color.btn_bg_color), editInputEmail);
                    setUpperHintColor(getResources().getColor(R.color.btn_bg_color), editInputWedding);
                    mobile.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    designation.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    doj.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    zone.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    region.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    state.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    city.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    dealer.setTextColor(getResources().getColor(R.color.btn_bg_color));
                    cameraButton.startAnimation(AnimationUtils.loadAnimation(MyProfileActivity.this, R.anim.zoomout));
                    cameraButton.hide();
                    slideToBottom(bottomLayout);
                    email.setEnabled(false);
                    checkBoxMarried.setEnabled(false);
                    dobCalendar.setVisibility(View.INVISIBLE);
                    weddingCalendar.setVisibility(View.INVISIBLE);
                    IMAGE_PATH = "";
                    isEditable = false;
                    setMyProfile();

                }

            }
        });

        cameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PickImageDialog.build(new PickSetup().setButtonOrientation(LinearLayout.HORIZONTAL)).setOnPickCancel(new IPickCancel() {
                    @Override
                    public void onCancelClick() {

                    }
                }).show(MyProfileActivity.this);
            }
        });

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


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

    }

    private void setUpperHintColor(int color, TextInputLayout txtInputLayout) {
        try {
            Field field = txtInputLayout.getClass().getDeclaredField("mFocusedTextColor");
            field.setAccessible(true);
            int[][] states = new int[][]{
                    new int[]{}
            };
            int[] colors = new int[]{
                    color
            };
            ColorStateList myList = new ColorStateList(states, colors);
            field.set(txtInputLayout, myList);

            Method method = txtInputLayout.getClass().getDeclaredMethod("updateLabelState", boolean.class);
            method.setAccessible(true);
            method.invoke(txtInputLayout, true);

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

    public String dateFormate(String dte) {
        String date = "";
        if (dte.equalsIgnoreCase("0000-00-00")) {
            date = "00/00/0000";
            return date;
        } else {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date newDate = null;
            try {
                newDate = format.parse(dte);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            format = new SimpleDateFormat("dd-MMM-yyyy");
            date = format.format(newDate);

        }
        return date;
    }

    public String finalDateFormat(String date) {

        SimpleDateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy");
        Date newDate = null;
        try {
            newDate = format1.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        format1 = new SimpleDateFormat("yyyy-MM-dd");
        date = format1.format(newDate);
        return date;

    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    public void slideToBottom(View view) {
        TranslateAnimation animate = new TranslateAnimation(0, 0, 0, view.getHeight());
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    public void slideToTop(View view) {
        TranslateAnimation animate = new TranslateAnimation(0, 0, view.getHeight(), 0);
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.VISIBLE);
    }

    private void getMyProfile() {
        if (new UtilService().isNetworkAvailable(MyProfileActivity.this)) {
            progressDialog = new TransparentProgressDialog(MyProfileActivity.this);
            progressDialog.show();

            try {
                restService.getProfile().enqueue(new Callback<UserResponse>() {
                    @Override
                    public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            MY_PROFILE = response.body();
                            if (MY_PROFILE.getData().getIs_married().equalsIgnoreCase("1")) {
                                checkBoxMarried.setChecked(true);
                                linearWeddingDate.setVisibility(View.GONE);
                            }
                            setMyProfile();
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                        }

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (getPreferences(MODE_PRIVATE).getBoolean("MyProfileActivity", true)) {
                                    showHelpScreen();
                                    getPreferences(MODE_PRIVATE).edit().putBoolean("MyProfileActivity", false).apply();
                                }
                            }
                        }, 1000);
                    }

                    @Override
                    public void onFailure(Call<UserResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

    private void setMyProfile() {

        email.setText(MY_PROFILE.getData().getEmailid());
        mobile.setText(MY_PROFILE.getData().getMobileno());
        dealer.setText(MY_PROFILE.getData().getDealer().getDealer_name());
        designation.setText(MY_PROFILE.getData().getRolename());
        doj.setText(dateFormate(MY_PROFILE.getData().getDoj()));
        zone.setText(MY_PROFILE.getData().getZone());
        region.setText(MY_PROFILE.getData().getZone());
        state.setText(MY_PROFILE.getData().getState());
        city.setText(MY_PROFILE.getData().getCity());
        dob.setText(dateFormate(MY_PROFILE.getData().getDob()));
        weddingDate.setText(dateFormate(MY_PROFILE.getData().getMarriage_date()));
        collapsingToolbar.setTitle(MY_PROFILE.getData().getFname() + " " + MY_PROFILE.getData().getLname());
        collapsingToolbar.setSubtitle(MY_PROFILE.getData().getRolename());
        Glide.with(this).load(MY_PROFILE.getData().getProfile_photo())
                .thumbnail(Glide.with(this).load(R.drawable.placeholder))
                .into(userImage);
    }

    @Override
    public void onPickResult(PickResult pickResult) {
        if (pickResult.getError() == null) {
            IMAGE_PATH = pickResult.getPath();
            if (IMAGE_PATH != null && !IMAGE_PATH.trim().isEmpty()) {
                Intent intent = new Intent(MyProfileActivity.this, CropActivity.class);
                CropActivity.mSourceUri = pickResult.getUri();
                startActivityForResult(intent, 2276);
            } else {
                userImage.setImageBitmap(pickResult.getBitmap());
            }

        } else {
            GlobalData.showToast(this, pickResult.getError().getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 2276) {
            IMAGE_PATH = data.getStringExtra("IMAGE_PATH");
            Glide.with(this).load(new File(IMAGE_PATH))
                    .thumbnail(Glide.with(this).load(R.drawable.gif_loader))
                    .into(userImage);
        } else if (resultCode == RESULT_CANCELED && requestCode == 2276) {
            IMAGE_PATH = "";
        }
    }

    private void showHelpScreen() {
        try {
            new FancyShowCaseView.Builder(this)
                    .focusOn(editButton)
                    .title("Tap here to edit profile details")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .focusShape(FocusShape.CIRCLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void updateProfile() {
        if (dob.getText().toString().trim().isEmpty() || dob.getText().toString().equalsIgnoreCase("00/00/0000")) {
            GlobalData.showToast(this, "Enter Date of Birth", Toast.LENGTH_SHORT).show();
            return;
        }

        if (email.getText().toString().trim().isEmpty()) {
            GlobalData.showToast(this, "Enter email", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isValidEmail(email.getText().toString())) {
            GlobalData.showToast(this, "Enter valid email address", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mobile.getText().toString().trim().isEmpty()) {
            GlobalData.showToast(this, "Enter mobile number", Toast.LENGTH_SHORT).show();
            return;
        }

        if (checkBoxMarried.isChecked()) {
            if (weddingDate.getText().toString().trim().isEmpty() || weddingDate.getText().toString().equalsIgnoreCase("00/00/0000")) {
                GlobalData.showToast(this, "Enter wedding date", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if (new UtilService().isNetworkAvailable(MyProfileActivity.this)) {
            if (IMAGE_PATH.trim().isEmpty()) {
                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("dob", finalDateFormat(dob.getText().toString().trim()));
                    map.put("email", email.getText().toString().trim());
                    map.put("is_married", checkBoxMarried.isChecked() ? "1" : "0");
                    if (checkBoxMarried.isChecked()) {
                        map.put("marriage_date", finalDateFormat(weddingDate.getText().toString().trim()));
                    } else {
                        map.put("marriage_date", "0000-00-00");
                    }

                    progressDialog = new TransparentProgressDialog(MyProfileActivity.this);
                    progressDialog.show();
                    restService.postProfile(map).enqueue(new Callback<UserResponse>() {
                        @Override
                        public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {

                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }

                            if (response.body() != null && response.body().getStatus() == 200) {
                                MY_PROFILE = response.body();
                                GlobalData.showToast(MyProfileActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
                                setMyProfile();
                                GlobalData.user.setData(response.body().getData());
                                saveUserData();
                                new Handler(HomeActivity.profileUpdateCallback).sendEmptyMessage(0);

                            } else if (response.body() != null && response.body().getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            } else if (response.body() != null) {
                                GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            } else if (response.errorBody() != null) {
                                Gson gson = new Gson();
                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                                if (message.getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    finish();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<UserResponse> call, Throwable t) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            GlobalData.showToast(MyProfileActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                        }
                    });

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

            } else {
                File file = new File(IMAGE_PATH);
                RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
                RequestBody emailtxt = RequestBody.create(MediaType.parse("text/plain"), email.getText().toString().trim());
                RequestBody dobtxt = RequestBody.create(MediaType.parse("text/plain"), finalDateFormat(dob.getText().toString().trim()));
                RequestBody isMarried = RequestBody.create(MediaType.parse("text/plain"), checkBoxMarried.isChecked() ? "1" : "0");
                RequestBody isMarriedDate = RequestBody.create(MediaType.parse("text/plain"), "0000-00-00");
                if (checkBoxMarried.isChecked()) {
                    isMarriedDate = RequestBody.create(MediaType.parse("text/plain"), finalDateFormat(weddingDate.getText().toString().trim()));
                }
                progressDialog = new TransparentProgressDialog(MyProfileActivity.this);
                progressDialog.show();
                restService.postProfileWithImage(body, emailtxt, dobtxt, isMarried, isMarriedDate).enqueue(new Callback<UserResponse>() {
                    @Override
                    public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            MY_PROFILE = response.body();
                            GlobalData.showToast(MyProfileActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
                            setMyProfile();
                            GlobalData.user.setData(response.body().getData());
                            saveUserData();
                            new Handler(HomeActivity.profileUpdateCallback).sendEmptyMessage(0);

                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<UserResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        t.printStackTrace();
                        GlobalData.showToast(MyProfileActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } else {
            GlobalData.showToast(MyProfileActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void showInstructions() {
        View view = LayoutInflater.from(MyProfileActivity.this).inflate(
                R.layout.profile_success, null);
        TextView textHead = (TextView) view.findViewById(R.id.textHead);
        TextView text1 = (TextView) view.findViewById(R.id.text1);
        TextView text2 = (TextView) view.findViewById(R.id.text2);
        TextView text3 = (TextView) view.findViewById(R.id.text3);


        view.findViewById(R.id.btn_ok).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        startActivity(new Intent(MyProfileActivity.this, HomeActivity.class));
                    }
                });

        alertDialogBuilder = new AlertDialog.Builder(MyProfileActivity.this);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setView(view);
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }


    private void saveUserData() {
        editButton.performClick();
        GlobalData.sdb.delete("session", null, null);
        Gson gson = new Gson();
        JsonElement jsonElement = gson.toJsonTree(
                GlobalData.user, new TypeToken<UserResponse>() {
                }.getType());
        ContentValues values = new ContentValues();
        values.put("user", jsonElement.toString());
        GlobalData.sdb.insert("session", null, values);
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(MyProfileActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

