package com.retrytech.strangerapp.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioDeviceInfo;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowInsets;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.retrytech.strangerapp.R;
import com.retrytech.strangerapp.databinding.ActivityCallBinding;
import com.retrytech.strangerapp.databinding.ItemConfirmationPopupBinding;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.modal.searchuser.SearchUser;
import com.retrytech.strangerapp.modal.settings.AppSettings;
import com.retrytech.strangerapp.modal.token.AgoraToken;
import com.retrytech.strangerapp.retrofit.Const;
import com.retrytech.strangerapp.retrofit.RetrofitClient;
import com.retrytech.strangerapp.utils.SessionManager;
import com.retrytech.strangerapp.utils.ads.MyInterstitialAds;

import java.util.HashMap;

import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CallActivity extends AppCompatActivity implements Runnable {

    private static final int PERMISSION_REQ_ID = 22;

    // Ask for Android device permissions at runtime.
    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    ActivityCallBinding binding;
    User.Data userData;
    SessionManager sessionManager;
    boolean isCallBackPressed = false;
    private RtcEngine mRtcEngine;
    private boolean mCallEnd;
    private boolean mMuted;
    private CardView mLocalContainer;
    private RelativeLayout mRemoteContainer;
    private VideoCanvas mLocalVideo;
    private VideoCanvas mRemoteVideo;
    private ImageView mCallBtn;
    private ImageView mMuteBtn;
    private ImageView mSwitchCameraBtn;
    private String token;
    Handler handler = new Handler(Looper.getMainLooper());
    Handler fakeCallHandler = new Handler(Looper.getMainLooper());
    int gender = -1;
    private int coinsToReduce = 0;
    MyInterstitialAds myInterstitialAds;
    private Runnable runnable = () -> {
        if (sessionManager.getAppSettings().getGender().getIsFack() == 1) {
            startActivity(new Intent(CallActivity.this, FakeVideoActivity.class));
            deductCoinsFromWallet();
        }
        onBackPressed();
    };
    // Java
    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        @Override
        // Listen for the onJoinChannelSuccess callback.
        // This callback occurs when the local user successfully joins the channel.
        public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
            runOnUiThread(() -> Log.i("agora", "Join channel success, Channel: " + channel));
        }

        @Override
        public void onUserJoined(final int uid, int elapsed) {
            super.onUserJoined(uid, elapsed);
            runOnUiThread(() -> {
                getUserData();
                setupRemoteVideo(uid);
                deductCoinsFromWallet();
                fakeCallHandler.removeCallbacks(runnable);
            });
        }

        @Override
        public void onUserOffline(final int uid, int reason) {
            runOnUiThread(() -> {
                Log.i("agora", "User offline, uid: " + (uid & 0xFFFFFFFFL));
                onBackPressed();
                mCallEnd = true;
            });
        }
    };

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

            } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                if (mRtcEngine != null) {
                    mRtcEngine.setEnableSpeakerphone(false);
                    mRtcEngine.enableInEarMonitoring(false);
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

            } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {

            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                if (mRtcEngine != null) {
                    mRtcEngine.setEnableSpeakerphone(true);
                }
            }
        }
    };

    private void generateTokenAPI() {
        Call<AgoraToken> call = RetrofitClient.getService().generateToken(Const.API_KEY, sessionManager.getUser().getData().getIdentity(), Const.AGORA_APP_ID, Const.AGORA_APP_CERTIFICATE);
        call.enqueue(new Callback<AgoraToken>() {
            @Override
            public void onResponse(Call<AgoraToken> call, Response<AgoraToken> response) {
                if (response.body() != null) {
                    AgoraToken agoraToken = response.body();
                    token = agoraToken.getToken();
                    searchForUser();
                }
            }

            @Override
            public void onFailure(Call<AgoraToken> call, Throwable t) {

            }
        });
    }

    private void searchForUser() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", sessionManager.getUser().getData().getId());
        hashMap.put("token", token);
        if (gender == -1) {
            gender = sessionManager.getUser().getData().getGender();
        }
        hashMap.put("gender_type", gender);
        Call<SearchUser> call = RetrofitClient.getService().searchForCall(Const.API_KEY, hashMap);
        call.enqueue(new Callback<SearchUser>() {
            @Override
            public void onResponse(Call<SearchUser> call, Response<SearchUser> response) {
                if (response.body() != null) {
                    SearchUser searchUser = response.body();
//                    Log.d("TAG", "onResponse: " + searchUser.getData().get(0).getFullname());
                    userData = searchUser.getData().get(0);

                    if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                            checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                            checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
                        initEngineAndJoinChannel();

                        if (sessionManager.getUser().getData().getId() == userData.getId()) {
                            userData = null;
                            binding.loutLoader.tvSearching.setText(R.string.waiting_for_someone);
                            fakeCallHandler.postDelayed(runnable, sessionManager.getAppSettings().getGender().getFacktime() * 1000L);


                        } else {
                            String maxCallDurationStr = sessionManager.getAppSettings().getGender().getMaxcallduration();
                            if (maxCallDurationStr != null && !maxCallDurationStr.isEmpty())
                                handler.postDelayed(CallActivity.this, Integer.parseInt(maxCallDurationStr) * 1000L);
                            binding.loutLoader.loutLoader1.setVisibility(View.GONE);
                            deductCoinsFromWallet();
                        }
                        setData();
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchUser> call, Throwable t) {

            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
            return defaultInsets.replaceSystemWindowInsets(
                    defaultInsets.getSystemWindowInsetLeft(),
                    0,
                    defaultInsets.getSystemWindowInsetRight(),
                    defaultInsets.getSystemWindowInsetBottom());
        });
        ViewCompat.requestApplyInsets(decorView);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));

        binding = DataBindingUtil.setContentView(this, R.layout.activity_call);
        sessionManager = new SessionManager(this);
        initUI();
        myInterstitialAds = new MyInterstitialAds(this);
        gender = getIntent().getIntExtra("gender", -1);
        if (gender == 1 || gender == 0) {
            coinsToReduce = Integer.parseInt(sessionManager.getAppSettings().getGender().getGendermatch());
        } else {
            coinsToReduce = Integer.parseInt(sessionManager.getAppSettings().getGender().getBothMatch());
        }
        binding.loutLoader.defaultAdView.activity = this;
        binding.loutLoader.loutLoader1.setVisibility(View.VISIBLE);

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(mReceiver, filter);
        generateTokenAPI();
        binding.loutLoader.btnCancel.setOnClickListener(view -> {
            onBackPressed();
        });
        Glide.with(this).load(Const.ITEM_URL + sessionManager.getUser().getData().getImage()).circleCrop().into(binding.loutLoader.imgUser);

        binding.ivMenu.setOnClickListener(view -> {
            PopupMenu popupMenu = new PopupMenu(this, view);
            popupMenu.inflate(R.menu.call_menu);
            popupMenu.setOnMenuItemClickListener(item -> {
                if (item.getItemId() == R.id.menu_report) {
                    startActivity(new Intent(CallActivity.this, ReportActivity.class).putExtra("userId", userData.getId()));
                    onBackPressed();
                } else if (item.getItemId() == R.id.menu_block) {
                    Dialog dialog = new Dialog(this);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    View view1 = LayoutInflater.from(this).inflate(R.layout.item_confirmation_popup, null, false);
                    ItemConfirmationPopupBinding confirmationPopupBinding = DataBindingUtil.bind(view1);

                    if (confirmationPopupBinding != null) {
                        confirmationPopupBinding.tvMessage.setText(getResources().getString(R.string.block_acc_message));

                        confirmationPopupBinding.btnYes.setOnClickListener(v -> {
                            dialog.dismiss();
                            Call<User> call = RetrofitClient.getService().blockUserForUser(Const.API_KEY, sessionManager.getUser().getData().getId(),
                                    sessionManager.getUser().getData().getBlockedUsers() == null ? String.valueOf(userData.getId()) : sessionManager.getUser().getData().getBlockedUsers().concat(",").concat(String.valueOf(userData.getId())));
                            call.enqueue(new Callback<User>() {
                                @Override
                                public void onResponse(Call<User> call, Response<User> response) {

                                }

                                @Override
                                public void onFailure(Call<User> call, Throwable t) {

                                }
                            });
                            onBackPressed();
                        });
                        confirmationPopupBinding.btnCancel.setOnClickListener(v -> dialog.dismiss());
                        dialog.setContentView(confirmationPopupBinding.getRoot());
                        dialog.setCancelable(false);
                        dialog.show();
                    }
                }
                return true;
            });
            popupMenu.show();
        });


    }

    private boolean isHeadphonesPlugged() {
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        AudioDeviceInfo[] audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
        if (isBluetoothHeadsetConnected()) {
            return true;
        }
        for (AudioDeviceInfo deviceInfo : audioDevices) {
            if (deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                    || deviceInfo.getType() == AudioDeviceInfo.TYPE_WIRED_HEADSET || deviceInfo.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
                return true;
            }
        }
        return false;
    }

    public boolean isBluetoothHeadsetConnected() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {

            return false;
        }
        return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
                && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothAdapter.STATE_CONNECTED;
    }

    private void setData() {

        if (userData != null) {
            binding.loutAnswer.lnrMain.setVisibility(View.VISIBLE);
            binding.loutAnswer.tvName.setText(userData.getFullname());
            binding.tvUserLocation.setText(userData.getLocation());
            binding.tvUserName.setText(userData.getFullname());
            mRtcEngine.setEnableSpeakerphone(false);
            onLocalAudioMuteClicked(null);
            binding.loutAnswer.btnYes.setOnClickListener(v -> {
                binding.loutAnswer.lnrMain.setVisibility(View.GONE);
                if (isHeadphonesPlugged()) {
                    mRtcEngine.enableInEarMonitoring(false);
                    mRtcEngine.setEnableSpeakerphone(false);
                } else {
                    mRtcEngine.setEnableSpeakerphone(true);
                }
                onLocalAudioMuteClicked(v);
            });
            binding.loutAnswer.btnNo.setOnClickListener(v -> {
                onBackPressed();
            });
            Glide.with(this)
                    .load(Const.ITEM_URL + userData.getImage())
                    .circleCrop()
                    .into(binding.imgUser);
            Glide.with(this)
                    .load(Const.ITEM_URL + userData.getImage())
                    .circleCrop()
                    .into(binding.loutAnswer.ivProfile);
        }
    }

    private void initEngineAndJoinChannel() {
        initializeEngine();
        setupVideoConfig();
        setupLocalVideo();
        joinChannel();
        if (userData != null && userData.getId() != sessionManager.getUser().getData().getId()) {
            joinChannel();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID) &&
                checkSelfPermission(REQUESTED_PERMISSIONS[2], PERMISSION_REQ_ID)) {
            initEngineAndJoinChannel();

            if (sessionManager.getUser().getData().getId() == userData.getId()) {
                userData = null;
                binding.loutLoader.tvSearching.setText(R.string.waiting_for_someone);
                fakeCallHandler.postDelayed(runnable, sessionManager.getAppSettings().getGender().getFacktime() * 1000L);


            } else {
                String maxCallDurationStr = sessionManager.getAppSettings().getGender().getMaxcallduration();
                if (maxCallDurationStr != null && !maxCallDurationStr.isEmpty())
                    handler.postDelayed(CallActivity.this, Integer.parseInt(maxCallDurationStr) * 1000L);
                binding.loutLoader.loutLoader1.setVisibility(View.GONE);
                deductCoinsFromWallet();
            }
            setData();
        }
    }

    public void onLocalAudioMuteClicked(View view) {
        Log.d("TAG", "onLocalAudioMuteClicked: " + view);

        mMuted = !mMuted;
        // Stops/Resumes sending the local audio stream.
        mRtcEngine.muteLocalAudioStream(mMuted);


        int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
        mMuteBtn.setImageResource(res);
    }

    public void onSwitchCameraClicked(View view) {
        Log.d("TAG", "onSwitchCameraClicked: " + view);
        // Switches between front and rear cameras.
        mRtcEngine.switchCamera();
    }

    private void switchView(VideoCanvas canvas) {
        ViewGroup parent = removeFromParent(canvas);
        if (parent == mLocalContainer) {
            if (canvas.view instanceof SurfaceView) {
                ((SurfaceView) canvas.view).setZOrderMediaOverlay(false);
            }
            mRemoteContainer.addView(canvas.view);
        } else if (parent == mRemoteContainer) {
            if (canvas.view instanceof SurfaceView) {
                ((SurfaceView) canvas.view).setZOrderMediaOverlay(true);
            }
            mLocalContainer.addView(canvas.view);
        }
    }

    public void onLocalContainerClick(View view) {
        Log.d("TAG", "onLocalContainerClick: " + view);
        switchView(mLocalVideo);
        switchView(mRemoteVideo);
    }

    public void onCallClicked(View view) {
        Log.d("TAG", "onCallClicked: " + view);
        if (mCallEnd) {
            startCall();
            mCallEnd = false;
            mCallBtn.setImageResource(R.drawable.btn_endcall);
        } else {
            onBackPressed();
            mCallEnd = true;
        }

        showButtons(!mCallEnd);
    }

    private void showButtons(boolean show) {
        int visibility = show ? View.VISIBLE : View.GONE;
        mMuteBtn.setVisibility(visibility);
        mSwitchCameraBtn.setVisibility(visibility);
    }

    private void startCall() {
        setupLocalVideo();
        joinChannel();
    }

    private void endCall() {
        fakeCallHandler.removeCallbacks(runnable);
        mCallEnd = true;
        removeFromParent(mLocalVideo);
        mLocalVideo = null;
        removeFromParent(mRemoteVideo);
        mRemoteVideo = null;
        mRtcEngine.setExternalVideoSource(true, false, true);
        leaveChannel();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        handler.removeCallbacks(this);
        handler.removeCallbacks(this);
        endCall();
        RtcEngine.destroy();
        callingHandler.removeCallbacks(callingRunnable);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        myInterstitialAds.showAds();
        isCallBackPressed = false;
        mCallEnd = true;
//        endCall();
        setResult(RESULT_OK);
        super.onBackPressed();

    }

    private void resetUserCallStatus() {

        Call<User> call = RetrofitClient.getService().resetUserCallStatus(Const.API_KEY, sessionManager.getUser().getData().getId());
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.body() != null) {
                    User user = response.body();

                    RtcEngine.destroy();
                    if (user.isStatus() && !isCallBackPressed) {
                        finish();
                        isCallBackPressed = true;
                    }

                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                if (!isDestroyed()) {
                    CallActivity.super.onBackPressed();
                }
            }
        });

    }


    private void leaveChannel() {
        if (mRtcEngine != null) {
            mRtcEngine.leaveChannel();
        }
        resetUserCallStatus();


    }

    private ViewGroup removeFromParent(VideoCanvas canvas) {
        if (canvas != null) {
            ViewParent parent = canvas.view.getParent();
            if (parent != null) {
                ViewGroup group = (ViewGroup) parent;
                group.removeView(canvas.view);
                return group;
            }
        }
        return null;
    }

    private void setupVideoConfig() {
        mRtcEngine.enableVideo();
        mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
                VideoEncoderConfiguration.VD_640x360,
                VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
                VideoEncoderConfiguration.STANDARD_BITRATE,
                VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
    }

    private boolean checkSelfPermission(String permission, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return true;
        }
        if (ContextCompat.checkSelfPermission(this, permission) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
            return false;
        }
        return true;
    }

    // Initialize the RtcEngine object.
    private void initializeEngine() {
        try {
            mRtcEngine = RtcEngine.create(getBaseContext(), Const.AGORA_APP_ID, mRtcEventHandler);

        } catch (Exception e) {
            Log.e("TAG", Log.getStackTraceString(e));
        }
    }

    private void initUI() {
        mLocalContainer = findViewById(R.id.local_video_view_container);
        mRemoteContainer = findViewById(R.id.remote_video_view_container);

        mCallBtn = findViewById(R.id.btn_call);
        mMuteBtn = findViewById(R.id.btn_mute);
        mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);


    }

    private void setupLocalVideo() {

        // Enable the video module.Ca
        mRtcEngine.enableVideo();

        // Create a SurfaceView object.
        SurfaceView mLocalView = RtcEngine.CreateRendererView(getBaseContext());
        mLocalView.setZOrderMediaOverlay(true);
        mLocalContainer.addView(mLocalView);
        // Set the local video view.
        mLocalVideo = new VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0);
        mRtcEngine.setupLocalVideo(mLocalVideo);
    }


    private void setupRemoteVideo(int uid) {

        // Create a SurfaceView object.
        SurfaceView mRemoteView = RtcEngine.CreateRendererView(getBaseContext());
        mRemoteContainer.addView(mRemoteView);
        // Set the remote video view.
        mRemoteVideo = new VideoCanvas(mRemoteView, VideoCanvas.RENDER_MODE_HIDDEN, uid);
        mRtcEngine.setupRemoteVideo(mRemoteVideo);

    }


    private void joinChannel() {
        mRtcEngine.joinChannel(userData.getToken(), userData.getIdentity(), "Extra Optional Data", 0);
    }

    Handler callingHandler = new Handler();
    long callingTime = 0;

    public void deductCoinsFromWallet() {
        Call<AppSettings> call = RetrofitClient.getService().removeCoins(Const.API_KEY, sessionManager.getUser().getData().getId(), coinsToReduce);
        call.enqueue(new Callback<AppSettings>() {
            @Override
            public void onResponse(Call<AppSettings> call, Response<AppSettings> response) {
                if (response.body() != null) {
                    AppSettings settings = response.body();

                    if (!settings.isStatus()) {
                        Log.d("TAG", "onResponse: " + settings.getMessage());
                    } else {
                        sessionManager.manageWallet(false, coinsToReduce);
                    }
                    callingHandler.postDelayed(callingRunnable, 60000);
                }
            }

            @Override
            public void onFailure(Call<AppSettings> call, Throwable t) {
                Log.d("TAG", "onResponse: " + t.getMessage());
            }
        });
    }

    Runnable callingRunnable = new Runnable() {
        @Override
        public void run() {
            callingTime += 1000;
            if (sessionManager.getUser().getData().getCoins() <= coinsToReduce) {
                onBackPressed();
                return;
            }
            coinsToReduce = sessionManager.getAppSettings().getGender().getCallPriceMin();
            deductCoinsFromWallet();
        }
    };


    private void getUserData() {
        Call<User> call = RetrofitClient.getService().getConnectedUser(Const.API_KEY, sessionManager.getUser().getData().getId(), token);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.body() != null) {
                    User user = response.body();

                    if (user.getData() != null) {
                        binding.loutLoader.loutLoader1.setVisibility(View.GONE);
                        userData = user.getData();
                        String maxCallDurationStr = sessionManager.getAppSettings().getGender().getMaxcallduration();
                        if (maxCallDurationStr != null && !maxCallDurationStr.isEmpty())
                            handler.postDelayed(CallActivity.this, Integer.parseInt(maxCallDurationStr) * 1000L);
                        setData();
                    }

                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }

    @Override
    public void run() {
        onBackPressed();
    }

}