package com.qboxus.tictic.activitesfragments.livestreaming.activities;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SnapHelper;

import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.OnProgressListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;
import com.downloader.request.DownloadRequest;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.qboxus.tictic.R;
import com.qboxus.tictic.activitesfragments.EditTextSheetFragment;
import com.qboxus.tictic.activitesfragments.livestreaming.adapter.LiveCommentsAdapter;
import com.qboxus.tictic.activitesfragments.livestreaming.adapter.LiveUserViewAdapter;
import com.qboxus.tictic.activitesfragments.livestreaming.adapter.TaggedLiveProductAdapter;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.InviteContactsToStreamFragment;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.PkBattleInviteFragment;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.PkBattleInviteSendFragment;
import com.qboxus.tictic.activitesfragments.livestreaming.model.CameraRequestModel;
import com.qboxus.tictic.activitesfragments.livestreaming.model.LiveCoinsModel;
import com.qboxus.tictic.activitesfragments.livestreaming.model.LiveCommentModel;
import com.qboxus.tictic.activitesfragments.livestreaming.model.LiveUserModel;
import com.qboxus.tictic.activitesfragments.livestreaming.model.PkInvitation;
import com.qboxus.tictic.activitesfragments.livestreaming.stats.LocalStatsData;
import com.qboxus.tictic.activitesfragments.livestreaming.stats.RemoteStatsData;
import com.qboxus.tictic.activitesfragments.livestreaming.stats.StatsData;
import com.qboxus.tictic.activitesfragments.profile.OptionSelectionSheetFragment;
import com.qboxus.tictic.activitesfragments.profile.ProfileActivity;
import com.qboxus.tictic.activitesfragments.profile.analytics.DateOperations;
import com.qboxus.tictic.activitesfragments.shoping.adapter.StreamingProductsAdapter;
import com.qboxus.tictic.activitesfragments.shoping.models.ProductModel;
import com.qboxus.tictic.apiclasses.ApiLinks;
import com.qboxus.tictic.databinding.ActivityMulticastStreamerBinding;
import com.qboxus.tictic.interfaces.AdapterClickListener;
import com.qboxus.tictic.interfaces.FragmentCallBack;
import com.qboxus.tictic.models.OptionSelectionModel;
import com.qboxus.tictic.models.StreamJoinModel;
import com.qboxus.tictic.models.StreamShowHeartModel;
import com.qboxus.tictic.models.UserModel;
import com.qboxus.tictic.simpleclasses.DateOprations;
import com.qboxus.tictic.simpleclasses.Dialogs;
import com.qboxus.tictic.simpleclasses.FileUtils;
import com.qboxus.tictic.simpleclasses.FirebaseFunction;
import com.qboxus.tictic.simpleclasses.Functions;
import com.qboxus.tictic.simpleclasses.OnSwipeTouchListener;
import com.qboxus.tictic.simpleclasses.TimerDialog;
import com.qboxus.tictic.simpleclasses.Variables;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.volley.plus.VPackages.VolleyRequest;
import com.volley.plus.interfaces.Callback;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import io.agora.rtc2.Constants;
import io.agora.rtc2.IRtcEngineEventHandler;
import io.agora.rtc2.video.VideoEncoderConfiguration;
import io.paperdb.Paper;


public class MulticastStreamerActivity extends RtcBaseActivity implements View.OnClickListener {

    private final long DELAY = 20000;
    public PkInvitation pkInvitation;
    DatabaseReference rootref;
    String userId, userName, userPicture;
    int userRole;
    String onlineType, description, secureCode, streamingId;
    int joinStreamPrice;
    boolean dualStreaming;
    LiveUserModel streamerLiveModel;
    Context context;
    boolean isFirstTimeFlip = true;
    LiveUserViewAdapter liveUserViewAdapter;
    ActivityMulticastStreamerBinding binding;


    ArrayList<ProductModel> pList = new ArrayList<>();

    ArrayList<LiveCommentModel> dataList = new ArrayList<>();
    RecyclerView recyclerView;
    LiveCommentsAdapter adapter;
    ValueEventListener productChildListener;
    // initailze the adapter
    ArrayList<ProductModel> productsList = new ArrayList<>();
    StreamingProductsAdapter productsAdapter;
    ChildEventListener commentChildListener;
    Calendar current_cal;
    ArrayList<StreamJoinModel> jointUserList = new ArrayList<>();
    ValueEventListener joinValueEventListener;
    ChildEventListener likeValueEventListener;
    int heartCounter = 0;
    ValueEventListener coinValueEventListener;
    ArrayList<LiveCoinsModel> senderCoinsList = new ArrayList<>();
    // check the current live user status eighter user is live or not when users goes offline this callback will hit
    ValueEventListener broadcastValueEventListener;
    ValueEventListener pkInvitationListener;
    PkBattleInviteSendFragment pkBattleInviteSendF;
    Dialog pkInvitationDialog;
    CountDownTimer pkInvitationTimer;
    CountDownTimer pkBattleCountDown;
    Handler winningHandler;
    Runnable winningRunnable;
    ArrayList<UserModel> taggedUserList = new ArrayList<>();
    boolean isAudioActivated = true, isVideoActivated = true, isbeautyActivated = true;
    ValueEventListener connectCheckListener;
    DatabaseReference connectedRef;
    SimpleDraweeView ivGiftProfile, ivGiftItem;
    LinearLayout tabGiftTitle;
    RelativeLayout tabGiftMain;
    View animationGiftCapture, animationResetAnimation;
    TextView tvGiftTitle, tvGiftCountTitle, tvSendGiftCount;
    MediaPlayer audio;
    MediaPlayer player;
    Handler handler;
    ValueEventListener cameraRequestEventListener;
    private VideoEncoderConfiguration.VideoDimensions mVideoDimension;
    private Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Functions.setLocale(Functions.getSharedPreference(this).getString(Variables.APP_LANGUAGE_CODE, Variables.DEFAULT_LANGUAGE_CODE)
                , this, getClass(), false);
        binding = DataBindingUtil.setContentView(MulticastStreamerActivity.this,
                R.layout.activity_multicast_streamer);

        context = MulticastStreamerActivity.this;
        rootref = FirebaseDatabase.getInstance().getReference();

        Intent bundle = getIntent();
        if (bundle != null) {
            userId = bundle.getStringExtra("userId");

            Functions.printLog(com.qboxus.tictic.Constants.tag, userId);

            userName = bundle.getStringExtra("userName");
            userPicture = bundle.getStringExtra("userPicture");
            userRole = bundle.getIntExtra("userRole", Constants.CLIENT_ROLE_BROADCASTER);
            onlineType = bundle.getStringExtra("onlineType");
            secureCode = bundle.getStringExtra("secureCode");
            dualStreaming = bundle.getBooleanExtra("dualStreaming", false);
            joinStreamPrice = bundle.getIntExtra("joinStreamPrice", 0);
            streamingId = bundle.getStringExtra("streamingId");
            pList = (ArrayList<ProductModel>) bundle.getSerializableExtra("productList");

        }

        InitControl();
        startLive();

    }

    void startLive() {

                ActionControl();

                if (userRole == Constants.CLIENT_ROLE_BROADCASTER) {
                    rootref.child("LiveStreamingUsers").child(streamingId).keepSynced(true);
                    rootref.child("LiveStreamingUsers").child(streamingId).onDisconnect().removeValue();

                    addFirebaseNode();
                    sendLiveNotification();
                    broadcasterlistenerNode();
                    addStreamInternetConnection();
                    addNodeCameraRequest();
                }

                ListenerCoinNode();
                addLikeStream();
                ListenerJoinNode();
                ListCommentData();
                addProductListener();
                addPkInvitationListener();

                setUpScreenData();

            }



    private void setUpScreenData() {
        binding.topBtnLayout.setVisibility(View.VISIBLE);
        binding.bottomBtnLayout.setVisibility(View.VISIBLE);
        String verified = Functions.getSharedPreference(context).getString(Variables.U_WALLET, "0");
        if (verified.equals("1")) {
            binding.ivVerified.setVisibility(View.VISIBLE);
        } else {
            binding.ivVerified.setVisibility(View.GONE);
        }
        binding.tvCoinCount.setText(Functions.getSharedPreference(context).getString(Variables.U_WALLET, "0"));
        binding.tvMainUserName.setText(userName);
        binding.ivMainProfile.setController(Functions.frescoImageLoad(userPicture, binding.ivMainProfile, false));

    }

    private void InitControl() {

        binding.tvMessage.setOnClickListener(this);
        binding.tabpk.setOnClickListener(this);

        //  binding.streamLikeView.setOnClickListener(this);
        binding.ivVideoRequest.setOnClickListener(this);
        binding.ivMuteJoinInvitation.setOnClickListener(this);

        binding.liveVideoGridLayout.setMainParentLayout(binding.videoGridMainLayout);


        initCommentAdapter();
        setUpJoinRecycler();
        initUI();
        initData();
    }


    private void ActionControl() {
        findViewById(R.id.cross_btn).setOnClickListener(this);
        findViewById(R.id.cross_btn2).setOnClickListener(this);

        final Animation inAnim = AnimationUtils.loadAnimation(context, R.anim.in_from_right);
        final Animation outAnim = AnimationUtils.loadAnimation(context, R.anim.out_to_left);
        final Animation inPrevAnim = AnimationUtils.loadAnimation(context, R.anim.in_from_left);
        final Animation outPrevAnim = AnimationUtils.loadAnimation(context, R.anim.out_to_right);


        binding.tabMainView.setOnTouchListener(new OnSwipeTouchListener(context) {
            public void onSwipeTop() {

            }

            public void onSwipeRight() {

                binding.viewflliper.setInAnimation(inPrevAnim);
                binding.viewflliper.setOutAnimation(outPrevAnim);
                binding.innerViewflliper.setInAnimation(inPrevAnim);
                binding.innerViewflliper.setOutAnimation(outPrevAnim);
                Log.d(com.qboxus.tictic.Constants.tag, "start");

                if (binding.viewTwo == binding.viewflliper.getCurrentView()) {
                    if (binding.viewFour == binding.innerViewflliper.getCurrentView()) {
                        binding.innerViewflliper.showPrevious();
                    } else {
                        binding.viewflliper.showPrevious();
                    }
                } else {
                    binding.viewflliper.showPrevious();
                }

            }

            public void onSwipeLeft() {
                binding.viewflliper.setInAnimation(inAnim);
                binding.viewflliper.setOutAnimation(outAnim);
                binding.innerViewflliper.setInAnimation(inAnim);
                binding.innerViewflliper.setOutAnimation(outAnim);
                Log.d(com.qboxus.tictic.Constants.tag, "end");
                if (binding.viewTwo == binding.viewflliper.getCurrentView()) {
                    if (binding.viewThree == binding.innerViewflliper.getCurrentView()) {
                        binding.innerViewflliper.showNext();
                    }

                } else {
                    binding.viewflliper.showNext();
                }
            }

            public void onSwipeBottom() {

            }

            public void onDoubleClick() {

            }

            public void onSingleClick() {

            }
        });

        if (isFirstTimeFlip) {
            isFirstTimeFlip = false;
            if (binding.viewOne == binding.viewflliper.getCurrentView()) {
                binding.viewflliper.showNext();
            }
        }

        binding.tabEffects.setOnClickListener(this);
        binding.tabMenu.setOnClickListener(this);
        binding.tabShareStream.setOnClickListener(this);


    }

    public void initCommentAdapter() {
        dataList.clear();
        recyclerView = findViewById(R.id.recylerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.setHasFixedSize(true);

        adapter = new LiveCommentsAdapter(context, dataList, new AdapterClickListener() {
            @Override
            public void onItemClick(View view, int pos, Object object) {
                LiveCommentModel itemUpdate = dataList.get(pos);
                if (view.getId() == R.id.profileImage) {
                    openProfile(itemUpdate.userId);
                } else if (view.getId() == R.id.username) {
                    openProfile(itemUpdate.userId);
                } else if (itemUpdate.getType().equals("shareStream")) {
                    inviteFriendsForStream();
                } else if (itemUpdate.getType().equals("selfInviteForStream")) {
                    if (streamerLiveModel.getDuetConnectedUserId() != null && !(TextUtils.isEmpty(streamerLiveModel.getDuetConnectedUserId()))) {
                        Toast.makeText(context, context.getString(R.string.user_already_connect_to_streaming), Toast.LENGTH_SHORT).show();
                    } else {
                        showCameraRequest(itemUpdate.getUserId());
                    }

                } else {
                    openProfile(itemUpdate.userId);
                }
            }
        });
        recyclerView.setAdapter(adapter);

    }

    public void openProfile(String userId) {
        if (Functions.checkProfileOpenValidation(userId)) {
            Intent intent = new Intent(this, ProfileActivity.class);
            intent.putExtra("user_id", userId);
            startActivity(intent);
            overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        }
    }

    public void addProductListener() {
        if (productChildListener == null) {
            initproductAdapter();
            Functions.printLog(com.qboxus.tictic.Constants.tag, "addProductListener");

            productChildListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    Functions.printLog(com.qboxus.tictic.Constants.tag, dataSnapshot.toString());
                    productsList.clear();
                    if (dataSnapshot.exists()) {
                        binding.productRecylerVeiw.setVisibility(View.VISIBLE);
                        for (DataSnapshot product : dataSnapshot.getChildren()) {
                            ProductModel model = product.getValue(ProductModel.class);
                            productsList.add(model);

                        }
                        productsAdapter.notifyDataSetChanged();

                    } else {

                        binding.productRecylerVeiw.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Functions.printLog(com.qboxus.tictic.Constants.tag, databaseError.toString());
                    binding.productRecylerVeiw.setVisibility(View.GONE);
                }
            };

            rootref.child("LiveStreamingUsers").child(streamingId).child("productsList").addValueEventListener(productChildListener);
        }
    }

    public void removeProductListener() {
        if (rootref != null && productChildListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("productsList").removeEventListener(productChildListener);
            productChildListener = null;
        }
    }

    public void initproductAdapter() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        binding.productRecylerVeiw.setLayoutManager(linearLayoutManager);
        binding.productRecylerVeiw.setHasFixedSize(true);

        SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(binding.productRecylerVeiw);


        productsAdapter = new StreamingProductsAdapter(context, productsList, new AdapterClickListener() {
            @Override
            public void onItemClick(View view, int pos, Object object) {

//                AllBusinessMenuModel item = productsList.get(pos);
//                if (item.getBussinessType().equals("1"))
//                {
//                    MenuItemList model = item.getMenuItemModel();
//
//                    TaggedProductDetailFragment fragment = new TaggedProductDetailFragment();
//                    Bundle args = new Bundle();
//                    args.putParcelable("data", model);
//                    args.putParcelable("storeModel", model.getStore());
//                    args.putString("type", "store");
//                    fragment.setArguments(args);
//                    fragment.show(getSupportFragmentManager(), "TaggedProductDetailF2");
//                } else if (item.getBussinessType().equals("2"))
//                {
//                    StoreDishes model=item.getStoreModel();
//                    TaggedCustomProductDetailFragment fragment = new TaggedCustomProductDetailFragment();
//                    Bundle args = new Bundle();
//                    args.putParcelable("storeModel", model);
//                    UserModel userModel=new UserModel();
//                    userModel.id = userId;
//                    userModel.username = userName;
//                    userModel.setProfilePic(userPicture);
//                    args.putParcelable("userModel",userModel);
//                    fragment.setArguments(args);
//                    fragment.show(getSupportFragmentManager(), "TaggedProductDetailF3");
//                }


            }
        });
        binding.productRecylerVeiw.setAdapter(productsAdapter);

    }

    private void showCameraRequest(String requestedUserId) {
        final Dialog alertDialog = new Dialog(context);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.setContentView(R.layout.camera_request_broadcast_view);
        alertDialog.getWindow().setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.d_round_white_background));

        RelativeLayout tabAccept = alertDialog.findViewById(R.id.tabAccept);
        RelativeLayout tabReject = alertDialog.findViewById(R.id.tabReject);
        ImageView closeBtn = alertDialog.findViewById(R.id.closeBtn);

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                HashMap<String, Object> duetConnectedUserMap = new HashMap<>();
                duetConnectedUserMap.put("duetConnectedUserId", "");
                rootref.child("LiveStreamingUsers").child(streamingId)
                        .updateChildren(duetConnectedUserMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (task.isComplete()) {
                                            sendCameraRequest("0", requestedUserId);
                                        }
                                    }
                                });
                            }
                        });

            }
        });
        tabAccept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                HashMap<String, Object> duetConnectedUserMap = new HashMap<>();
                duetConnectedUserMap.put("duetConnectedUserId", requestedUserId);
                rootref.child("LiveStreamingUsers").child(streamingId)
                        .updateChildren(duetConnectedUserMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (task.isComplete()) {
                                            sendCameraRequest("2", requestedUserId);
                                        }
                                    }
                                });
                            }
                        });
            }
        });
        tabReject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                HashMap<String, Object> duetConnectedUserMap = new HashMap<>();
                duetConnectedUserMap.put("duetConnectedUserId", "");
                rootref.child("LiveStreamingUsers").child(streamingId)
                        .updateChildren(duetConnectedUserMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (task.isComplete()) {
                                            sendCameraRequest("0", requestedUserId);
                                        }
                                    }
                                });
                            }
                        });

            }
        });
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    private void sendCameraRequest(String type, String requestedUserId) {
        CameraRequestModel model = new CameraRequestModel();
        model.setRequestState(type);
        rootref.child("LiveStreamingUsers").child(streamingId)
                .child("CameraRequest")
                .child(requestedUserId)
                .setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isComplete()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (type.equals("2")) {
                                        Toast.makeText(context, context.getString(R.string.camera_request_accepted), Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(context, context.getString(R.string.camera_request_sended), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });


    }

    public void ListCommentData() {
        current_cal = Calendar.getInstance();
        if (commentChildListener == null) {


//
//            LiveCommentModel model=new LiveCommentModel();
//            model.setType("alert");
//            model.setComment(getString(R.string.streaming_welcome_txt));
//            dataList.add(model);
//            adapter.notifyDataSetChanged();


            commentChildListener = new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                    LiveCommentModel model = dataSnapshot.getValue(LiveCommentModel.class);
                    dataList.add(model);

                    if (DateOprations.checkTimeDiffernce(current_cal, model.getCommentTime())) {
                        if (model.getType().equalsIgnoreCase("gift")) {
                            MulticastStreamerActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ShowGiftAnimation(model);
                                }
                            });
                        }
                    }


                    adapter.notifyDataSetChanged();
                    recyclerView.scrollToPosition(dataList.size() - 1);

                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            };
            rootref.child("LiveStreamingUsers").child(streamingId).child("Chat").addChildEventListener(commentChildListener);
        }
    }

    public void removeCommentListener() {
        if (rootref != null && commentChildListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("Chat").removeEventListener(commentChildListener);
            commentChildListener = null;
        }
    }

    private void setUpJoinRecycler() {
        GridLayoutManager layoutManager = new GridLayoutManager(context, 2);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        binding.liveUserViewRecyclerView.setLayoutManager(layoutManager);
        liveUserViewAdapter = new LiveUserViewAdapter(context, jointUserList, new AdapterClickListener() {
            @Override
            public void onItemClick(View view, int pos, Object object) {
                StreamJoinModel model = (StreamJoinModel) object;
                Log.d(com.qboxus.tictic.Constants.tag, model.getUserName());
            }
        });
        binding.liveUserViewRecyclerView.setAdapter(liveUserViewAdapter);
    }

    private void ListenerJoinNode() {
        if (joinValueEventListener == null) {
            joinValueEventListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    jointUserList.clear();
                    if (dataSnapshot.exists()) {
                        for (DataSnapshot joinSnapsot : dataSnapshot.getChildren()) {
                            Log.d(com.qboxus.tictic.Constants.tag, "Data JSON : " + joinSnapsot.getValue().toString());
                            if (!(TextUtils.isEmpty(joinSnapsot.getValue().toString()))) {
                                StreamJoinModel model = joinSnapsot.getValue(StreamJoinModel.class);
                                jointUserList.add(model);
                            }

                        }
                        liveUserViewAdapter.notifyDataSetChanged();
                        binding.liveUserCount.setText(Functions.getSuffix("" + jointUserList.size()));

                    } else {
                        liveUserViewAdapter.notifyDataSetChanged();
                        binding.liveUserCount.setText(Functions.getSuffix("" + jointUserList.size()));
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    liveUserViewAdapter.notifyDataSetChanged();
                    binding.liveUserCount.setText(Functions.getSuffix("" + jointUserList.size()));
                }
            };
            rootref.child("LiveStreamingUsers").child(streamingId).child("JoinStream")
                    .addValueEventListener(joinValueEventListener);
        }
    }

    public void removeJoinListener() {
        if (rootref != null && joinValueEventListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("JoinStream").removeEventListener(joinValueEventListener);
            joinValueEventListener = null;
        }
    }

    private void addLikeStream() {
        if (likeValueEventListener == null) {

            likeValueEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                    if (snapshot.exists()) {
                        StreamShowHeartModel likeData = snapshot.getValue(StreamShowHeartModel.class);
                        MulticastStreamerActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                heartCounter = heartCounter + 1;
                                binding.tvOtherUserLikes.setText(Functions.getSuffix("" + heartCounter) + " " + context.getString(R.string.likes));
                                //  heartsShow();
                            }
                        });
                    }
                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot snapshot) {

                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            };
            rootref.child("LiveStreamingUsers").child(streamingId).child("LikesStream").addChildEventListener(likeValueEventListener);

        }
    }

    private void ListenerCoinNode() {
        coinValueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                senderCoinsList.clear();
                if (dataSnapshot.exists()) {
                    for (DataSnapshot joinSnapsot : dataSnapshot.getChildren()) {
                        if (!(TextUtils.isEmpty(joinSnapsot.getValue().toString()))) {
                            LiveCoinsModel model = joinSnapsot.getValue(LiveCoinsModel.class);
                            senderCoinsList.add(model);
                        }
                    }
                    double maxCoins = 0;
                    LiveCoinsModel highCoinSender = null;
                    if (senderCoinsList.size() > 0) {
                        binding.tabCoinSender.setVisibility(View.VISIBLE);
                        maxCoins = Double.valueOf(senderCoinsList.get(0).getSendedCoins());
                        highCoinSender = senderCoinsList.get(0);
                    } else {
                        binding.tabCoinSender.setVisibility(View.GONE);
                    }
                    for (LiveCoinsModel item : senderCoinsList) {
                        if (Double.valueOf(item.getSendedCoins()) > maxCoins) {
                            maxCoins = Double.valueOf(item.getSendedCoins());
                            highCoinSender = item;
                        }
                    }
                    if (highCoinSender != null) {
                        binding.tvSender.setText(highCoinSender.getUserName());
                        binding.ivSender.setController(Functions.frescoImageLoad(highCoinSender.getUserPic(), binding.ivSender, false));
                    }


                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };
        rootref.child("LiveStreamingUsers").child(streamingId).child("CoinsStream").addValueEventListener(coinValueEventListener);
    }

    public void removeCoinListener() {
        if (rootref != null && coinValueEventListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("CoinsStream").removeEventListener(coinValueEventListener);
        }
    }

    // initialize the views of activity
    private void initUI() {
        boolean isBroadcaster = (userRole == Constants.CLIENT_ROLE_BROADCASTER);


        isAudioActivated = !isBroadcaster;
        isVideoActivated = !isBroadcaster;

//        isbeautyActivated=false;
//        rtcEngine().setBeautyEffectOptions(isbeautyActivated,
//                com.qboxus.tictic.activitesfragments.livestreaming.Constants.DEFAULT_BEAUTY_OPTIONS);

        binding.liveVideoGridLayout.setStatsManager(statsManager());

        rtcEngine().setClientRole(userRole);
        if (isBroadcaster) startBroadcast();
    }

    private void initData() {
        mVideoDimension = com.qboxus.tictic.activitesfragments.livestreaming.Constants.VIDEO_DIMENSIONS[
                config().getVideoDimenIndex()];
    }

    private void startBroadcast() {
        rtcEngine().setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
        SurfaceView surface = prepareRtcVideo(Integer.parseInt(config().getUid()), true);
        binding.liveVideoGridLayout.addUserVideoSurface(Integer.parseInt(config().getUid()), surface, true);
    }

    private void stopBroadcast() {
        rtcEngine().setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
        removeRtcVideo(Integer.parseInt(config().getUid()), true);
        binding.liveVideoGridLayout.removeUserVideo(Integer.parseInt(config().getUid()), true);
    }

    @Override
    public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("streamUid", uid);
        rootref.child("LiveStreamingUsers").child(streamingId).updateChildren(map);

    }

    @Override
    public void onUserJoined(int uid, int elapsed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Functions.printLog(com.qboxus.tictic.Constants.tag, "onUserJoined" + uid);
                renderRemoteUser(uid);
            }
        });
    }

    @Override
    public void onUserOffline(final int uid, int reason) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Functions.printLog(com.qboxus.tictic.Constants.tag, "onUserOffline" + uid);
                if (pkInvitation != null) {
                    if (pkInvitation.senderId.equals("" + uid) || pkInvitation.receiverId.equals("" + uid)) {
                        removeRemoteUser(uid);
                    }
                } else {
                    removeRemoteUser(uid);
                }
            }
        });
    }

    @Override
    public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                renderRemoteUser(uid);
            }
        });
    }

    private void renderRemoteUser(int uid) {
        SurfaceView surface = prepareRtcVideo(uid, false);
        binding.liveVideoGridLayout.addUserVideoSurface(uid, surface, false);
    }

    private void removeRemoteUser(int uid) {

        removeRtcVideo(uid, false);
        binding.liveVideoGridLayout.removeUserVideo(uid, false);
        stopPkBattleStreaming();

    }

    @Override
    public void onLocalVideoStats(IRtcEngineEventHandler.LocalVideoStats stats) {
        if (!statsManager().isEnabled()) return;

        LocalStatsData data = (LocalStatsData) statsManager().getStatsData(Integer.parseInt(config().getUid()));
        if (data == null) return;

        data.setWidth(mVideoDimension.width);
        data.setHeight(mVideoDimension.height);
        data.setFramerate(stats.sentFrameRate);
    }

    @Override
    public void onRtcStats(IRtcEngineEventHandler.RtcStats stats) {

        if (!(streamingId.equals("")) && (streamingId != null)) {
            Paper.book("MyLiveStreaming").write(streamingId, DateOprations.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        }

        if (!statsManager().isEnabled()) return;
        LocalStatsData data = (LocalStatsData) statsManager().getStatsData(Integer.parseInt(config().getUid()));
        if (data == null) return;

        data.setLastMileDelay(stats.lastmileDelay);
        data.setVideoSendBitrate(stats.txVideoKBitRate);
        data.setVideoRecvBitrate(stats.rxVideoKBitRate);
        data.setAudioSendBitrate(stats.txAudioKBitRate);
        data.setAudioRecvBitrate(stats.rxAudioKBitRate);
        data.setCpuApp(stats.cpuAppUsage);
        data.setCpuTotal(stats.cpuAppUsage);
        data.setSendLoss(stats.txPacketLossRate);
        data.setRecvLoss(stats.rxPacketLossRate);
    }

    // check the network quality
    @Override
    public void onNetworkQuality(int uid, int txQuality, int rxQuality) {
        if (!statsManager().isEnabled()) return;

        Functions.printLog(com.qboxus.tictic.Constants.tag, "onNetworkQuality:" + txQuality + ":" + rxQuality);
        StatsData data = statsManager().getStatsData(uid);
        if (data == null) return;

        data.setSendQuality(statsManager().qualityToString(txQuality));
        data.setRecvQuality(statsManager().qualityToString(rxQuality));
    }

    @Override
    public void onRemoteVideoStats(IRtcEngineEventHandler.RemoteVideoStats stats) {
        if (!statsManager().isEnabled()) return;

        RemoteStatsData data = (RemoteStatsData) statsManager().getStatsData(stats.uid);
        if (data == null) return;

        data.setWidth(stats.width);
        data.setHeight(stats.height);
        data.setFramerate(stats.rendererOutputFrameRate);
        data.setVideoDelay(stats.delay);
    }

    @Override
    public void onRemoteAudioStats(IRtcEngineEventHandler.RemoteAudioStats stats) {
        if (!statsManager().isEnabled()) return;

        RemoteStatsData data = (RemoteStatsData) statsManager().getStatsData(stats.uid);
        if (data == null) return;

        data.setAudioNetDelay(stats.networkTransportDelay);
        data.setAudioNetJitter(stats.jitterBufferDelay);
        data.setAudioLoss(stats.audioLossRate);
        data.setAudioQuality(statsManager().qualityToString(stats.quality));
    }

    @Override
    public void finish() {
        super.finish();
        statsManager().clearAllData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FirebaseFunction.deleteImageFromFirebase(userPicture);

        if (userRole == Constants.CLIENT_ROLE_BROADCASTER) {
            broadcastRemoveListener();
            removeNode();
            removeNodeCameraRequest();
            removeStreamInternetConnection();
        }

        removePkInvitationListener();
        removeCoinListener();
        removeLikeStream();
        removeJoinListener();
        removeCommentListener();
        removeProductListener();

    }

    public void removeLikeStream() {
        if (rootref != null && likeValueEventListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("LikesStream").removeEventListener(likeValueEventListener);
            likeValueEventListener = null;
        }
    }

    public void addFirebaseNode() {
        LiveUserModel model = new LiveUserModel();
        model.setStreamingId(streamingId);
        model.setUserId(userId);
        model.setUserName(userName);
        model.setUserPicture(userPicture);
        model.setOnlineType(onlineType);
        model.setDescription(description);
        model.setSecureCode(secureCode);
        model.isDualStreaming = dualStreaming;
        model.isStreamJoinAllow = dualStreaming;
        model.setJoinStreamPrice("" + joinStreamPrice);
        model.setUserCoins("0");
        model.setIsVerified(Functions.getSharedPreference(MulticastStreamerActivity.this).getInt(Variables.IS_VERIFIED, 0));
        model.setDuetConnectedUserId("");
        model.streamUid = -1;
        model.productsList = pList;
        rootref.child("LiveStreamingUsers").child(streamingId).setValue(model);
    }

    // when user goes to offline then change the value status on firebase
    public void removeNode() {
        if (pkInvitation != null) {
            rootref.child("LiveStreamingUsers").child(pkInvitation.senderStreamingId).child("pkInvitation").removeValue();
            rootref.child("LiveStreamingUsers").child(pkInvitation.receiverStreamingId).child("pkInvitation").removeValue();
        }
        rootref.child("LiveStreamingUsers").child(streamingId).removeValue();
    }

    public void broadcasterlistenerNode() {

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {

                broadcastValueEventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        if (dataSnapshot.exists()) {

                            streamerLiveModel = dataSnapshot.getValue(LiveUserModel.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    binding.tvCoinCount.setText(streamerLiveModel.getUserCoins());

                                    if (streamerLiveModel.isDualStreaming) {
                                        binding.ivMuteJoinInvitation.setVisibility(View.VISIBLE);
                                        if (streamerLiveModel.isStreamJoinAllow) {
                                            binding.ivMuteJoinInvitation.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_join_streaming_request));
                                        } else {
                                            binding.ivMuteJoinInvitation.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_join_streaming_request_mute));
                                        }

                                        if (streamerLiveModel.getDuetConnectedUserId() == null || streamerLiveModel.getDuetConnectedUserId().equals("")) {
                                            binding.ivVideoRequest.setVisibility(View.GONE);
                                        }
                                    } else {
                                        binding.ivMuteJoinInvitation.setVisibility(View.GONE);
                                    }

                                    Functions.getSharedPreference(MulticastStreamerActivity.this).edit()
                                            .putString(Variables.U_WALLET, streamerLiveModel.getUserCoins()).commit();
                                }
                            });
                        } else {
                            MulticastStreamerActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context, context.getString(R.string.your_live_channel_is_close), Toast.LENGTH_SHORT).show();
                                    onBackPressed();
                                }
                            });
                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                };
                rootref.child("LiveStreamingUsers").child(streamingId).addValueEventListener(broadcastValueEventListener);

            }

        }, 5000);
    }

    public void broadcastRemoveListener() {
        if (rootref != null && broadcastValueEventListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).removeEventListener(broadcastValueEventListener);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.tabShareStream: {
                inviteFriendsForStream();
            }
            break;
            case R.id.tabMenu: {
                ShowDailogForJoinBroadcast();
            }
            break;

            case R.id.cross_btn: {
                onBackPressed();
            }
            break;

            case R.id.cross_btn2: {
                if (pkInvitation != null) {
                    removePkBattle();
                } else {

                    onBackPressed();
                }
            }
            break;

            case R.id.tvMessage: {
                sendComment();
            }
            break;

            case R.id.ivVideoRequest: {
                if (streamerLiveModel.getDuetConnectedUserId() != null
                        && !(TextUtils.isEmpty(streamerLiveModel.getDuetConnectedUserId()))) {
                    showCameraRequest(streamerLiveModel.getDuetConnectedUserId());
                } else {
                    Toast.makeText(context, context.getString(R.string.no_user_connected), Toast.LENGTH_SHORT).show();
                }

            }
            break;

            case R.id.ivMuteJoinInvitation: {
                updateJoinInvitationStatus();
            }
            break;

            case R.id.tabpk: {
                openPkBattelInviteF();
            }
            break;
        }
    }

    public void addPkInvitationListener() {
        if (pkInvitationListener == null) {
            pkInvitationListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()) {

                        Log.d(com.qboxus.tictic.Constants.tag, snapshot.toString());

                        pkInvitation = snapshot.getValue(PkInvitation.class);

                        if (pkInvitation.action != null && pkInvitation.action.equals("1")) {

                            if (!config().getChannelName().equalsIgnoreCase(pkInvitation.pkStreamingId)) {
                                acceptPkBattleInvitation();
                                hideInvitationViews();
                            }

                            if (userId.equalsIgnoreCase(pkInvitation.senderId)) {
                                binding.coinCount1Txt.setText("" + pkInvitation.senderCoins);
                                binding.coinCount2Txt.setText("" + pkInvitation.receiverCoins);
                            }

                            if (userId.equalsIgnoreCase(pkInvitation.receiverId)) {
                                binding.coinCount1Txt.setText("" + pkInvitation.receiverCoins);
                                binding.coinCount2Txt.setText("" + pkInvitation.senderCoins);
                            }

                            updatePkBar();

                        } else if (pkInvitation.receiverId != null && pkInvitation.receiverId.equals(userId)) {

                            showPkInvitationDialog();
                        }

                    } else {
                        pkInvitation = null;
                        hideInvitationViews();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            };
            rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").addValueEventListener(pkInvitationListener);

        }
    }

    public void updatePkBar() {
        if (userId.equalsIgnoreCase(pkInvitation.senderId)) {
            int user1Coins = pkInvitation.senderCoins;
            int user2Coins = pkInvitation.receiverCoins;

            int total = user1Coins + user2Coins;
            if (total > 0) {
                int percentage1 = ((user1Coins * 100) / total);
                int percentage2 = 100 - percentage1;

                Functions.printLog(com.qboxus.tictic.Constants.tag, percentage1 + "--" + percentage2);

                binding.pkProgressbar.setFirstSectionPercentage(percentage1);
                binding.pkProgressbar.setSecondSectionPercentage(percentage2);
            } else {
                binding.pkProgressbar.setFirstSectionPercentage(50);
                binding.pkProgressbar.setSecondSectionPercentage(50);
            }

        } else if (userId.equalsIgnoreCase(pkInvitation.receiverId)) {
            int user1Coins = pkInvitation.receiverCoins;
            int user2Coins = pkInvitation.senderCoins;

            int total = user1Coins + user2Coins;
            if (total > 0) {
                int percentage1 = ((user1Coins * 100) / total);
                int percentage2 = 100 - percentage1;

                Functions.printLog(com.qboxus.tictic.Constants.tag, percentage1 + "--" + percentage2);

                binding.pkProgressbar.setFirstSectionPercentage(percentage1);
                binding.pkProgressbar.setSecondSectionPercentage(percentage2);
            } else {
                binding.pkProgressbar.setFirstSectionPercentage(50);
                binding.pkProgressbar.setSecondSectionPercentage(50);
            }
        }
    }

    public void removePkInvitationListener() {
        if (pkInvitationListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").removeEventListener(pkInvitationListener);

        }
    }

    public void openPkBattelInviteF() {
        PkBattleInviteFragment f = PkBattleInviteFragment.newInstance(new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle != null) {

                    LiveUserModel liveUserModel = bundle.getParcelable("data");
                    rootref.child("LiveStreamingUsers").child(liveUserModel.streamingId).child("pkInvitation").addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            if (!snapshot.exists()) {
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("senderId", userId);
                                map.put("senderName", userName);
                                map.put("senderPic", userPicture);
                                map.put("senderStreamingId", streamingId);

                                map.put("receiverStreamingId", liveUserModel.getStreamingId());
                                map.put("receiverId", liveUserModel.getUserId());
                                map.put("receiverName", liveUserModel.getUserName());
                                map.put("receiverPic", liveUserModel.getUserPicture());

                                map.put("action", "0");
                                map.put("senderCoins", 0);
                                map.put("receiverCoins", 0);
                                rootref.child("LiveStreamingUsers").child(liveUserModel.streamingId).child("pkInvitation").setValue(map);
                                rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").setValue(map);
                                openPkBattelInviteSendF(liveUserModel);
                            } else {
                                Functions.showToast(MulticastStreamerActivity.this, "The host is busy now. please try again later!");
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });


                }

            }
        });
        f.show(getSupportFragmentManager(), "PkBattleInviteF");
    }

    public void openPkBattelInviteSendF(LiveUserModel liveUserModel) {
        pkBattleInviteSendF = PkBattleInviteSendFragment.newInstance(streamingId, liveUserModel, new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
            }
        });
        pkBattleInviteSendF.show(getSupportFragmentManager(), "PkBattleInviteSendF");
    }

    public void showPkInvitationDialog() {
        pkInvitationDialog = new Dialog(MulticastStreamerActivity.this);
        pkInvitationDialog.setCancelable(false);
        pkInvitationDialog.setContentView(R.layout.show_double_button_new_popup_dialog);
        pkInvitationDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        final TextView tvtitle, tvMessage, tvPositive, tvNegative;
        tvtitle = pkInvitationDialog.findViewById(R.id.tvtitle);
        tvMessage = pkInvitationDialog.findViewById(R.id.tvMessage);
        tvNegative = pkInvitationDialog.findViewById(R.id.tvNegative);
        tvPositive = pkInvitationDialog.findViewById(R.id.tvPositive);


        tvtitle.setText("PK Invitation");
        tvMessage.setText(pkInvitation.senderName + " invite you to PK");
        tvNegative.setText("Reject");

        if (pkInvitationTimer != null)
            pkInvitationTimer.cancel();

        pkInvitationTimer = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long l) {
                tvPositive.setText("Accept(" + (int) (l / 1000) + ")");
            }

            @Override
            public void onFinish() {
                pkInvitationDialog.dismiss();
                rootref.child("LiveStreamingUsers").child(pkInvitation.senderStreamingId).child("pkInvitation").removeValue();
                rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").removeValue();

            }
        };
        pkInvitationTimer.start();

        tvNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pkInvitationDialog.dismiss();

                rootref.child("LiveStreamingUsers").child(pkInvitation.senderStreamingId).child("pkInvitation").removeValue();
                rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").removeValue();


            }
        });
        tvPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pkInvitationDialog.dismiss();
                String pkStreamingID = pkInvitation.senderStreamingId + "PK" + streamingId;

                Date c = Calendar.getInstance().getTime();
                final String formattedDate = Variables.df.format(c);


                HashMap<String, Object> map = new HashMap<>();
                map.put("action", "1");
                map.put("pkStreamingId", pkStreamingID);
                map.put("pkStreamingTime", formattedDate);
                map.put("timeStamp", ServerValue.TIMESTAMP);

                rootref.child("LiveStreamingUsers").child(pkInvitation.senderStreamingId).child("pkInvitation").updateChildren(map);
                rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").updateChildren(map);

            }
        });

        pkInvitationDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (pkInvitationTimer != null)
                    pkInvitationTimer.cancel();
            }
        });
        pkInvitationDialog.show();
    }


//    public void heartsShow()
//    {
//        binding.streamLikeView.addHeart(new Random().nextInt(5));
//    }

    public void acceptPkBattleInvitation() {
        rtcEngine().leaveChannel();
        config().setUid(Functions.getSharedPreference(this).getString(Variables.U_ID, ""));
        config().setChannelName(pkInvitation.pkStreamingId);
        rtcEngine().joinChannel(null, config().getChannelName(), "", Integer.parseInt(config().getUid()));

        startPkCountDown();
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showPkAnimation();
                    }
                });

            }
        }, 2500);


    }

    public void hideInvitationViews() {
        if (pkBattleInviteSendF != null) {
            pkBattleInviteSendF.dismiss();
        }

        if (pkInvitationDialog != null) {
            pkInvitationDialog.dismiss();
        }
    }

    public void showPkAnimation() {
        binding.pkgif.setVisibility(View.VISIBLE);
        ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(
                    String id,
                    @Nullable ImageInfo imageInfo,
                    @Nullable Animatable anim) {
                if (anim != null) {
                    // com-specific logic to enable animation starting
                    anim.start();
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    binding.pkgif.setVisibility(View.GONE);
                                }
                            });

                        }
                    }, 1800);
                    Functions.printLog(com.qboxus.tictic.Constants.tag, "onFinalImageSet");
                }
            }
        };
        ImageRequest request = ImageRequestBuilder.newBuilderWithResourceId(R.raw.ic_pk_battle2)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setAutoPlayAnimations(false)
                .setOldController(binding.pkgif.getController())
                .setControllerListener(controllerListener)
                .build();

        binding.pkgif.setController(controller);


    }

    public void removePkBattle() {
        if (pkInvitation != null) {
            if (userId.equalsIgnoreCase(Functions.getSharedPreference(this).getString(Variables.U_ID, ""))) {
                if (userId.equalsIgnoreCase(pkInvitation.senderId)) {
                    removeRemoteUser(Integer.parseInt(pkInvitation.receiverId));
                } else {
                    removeRemoteUser(Integer.parseInt(pkInvitation.senderId));
                }
            } else {
                removeRemoteUser(Integer.parseInt(userId));
            }
        }

    }

    public void stopPkBattleStreaming() {
        rootref.child("LiveStreamingUsers").child(streamingId).child("pkInvitation").removeValue();
        rtcEngine().leaveChannel();
        config().setUid(Functions.getSharedPreference(this).getString(Variables.U_ID, ""));
        config().setChannelName(streamingId);
        rtcEngine().joinChannel(null, config().getChannelName(), "", Integer.parseInt(config().getUid()));

        stopPkCountDown();
        hidePkBattleViews();
    }

    public void showPkBattleViews() {
        binding.pkProgressLayout.setVisibility(View.VISIBLE);
        binding.pkbattleTimerLayout.setVisibility(View.VISIBLE);
        binding.tabpk.setEnabled(false);
    }

    public void hidePkBattleViews() {
        binding.pkProgressLayout.setVisibility(View.GONE);
        binding.pkbattleTimerLayout.setVisibility(View.GONE);
        binding.tabpk.setEnabled(true);
    }

    public void startPkCountDown() {
        showPkBattleViews();

        if (pkBattleCountDown == null) {


            rootref.child(Variables.onlineUser).
                    child(Functions.getSharedPreference(getApplicationContext()).getString(Variables.U_ID, "0"))
                    .child("timeStamp").setValue(ServerValue.TIMESTAMP);

            rootref.child(Variables.onlineUser).
                    child(Functions.getSharedPreference(getApplicationContext()).getString(Variables.U_ID, "0")).addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            long value = (long) snapshot.child("timeStamp").getValue();
                            long dif = value - pkInvitation.timeStamp;
                            long timeDiffernce = com.qboxus.tictic.Constants.PkBattleTime - dif;

                            pkBattleCountDown = new CountDownTimer(timeDiffernce, 1000) {
                                @Override
                                public void onTick(long l) {
                                    binding.pkTimerTxt.setText(DateOperations.INSTANCE.getDate(l, "mm:ss"));
                                }

                                @Override
                                public void onFinish() {
                                    hidePkBattleViews();
                                    if (pkInvitation != null) {
                                        showWinningGif();
                                    }

                                }
                            };
                            pkBattleCountDown.start();

                            Functions.printLog(com.qboxus.tictic.Constants.tag, "difference..." + value);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });


        }
    }

    public void stopPkCountDown() {
        if (pkBattleCountDown != null) {
            pkBattleCountDown.cancel();
            pkBattleCountDown = null;
        }
    }

    public void showPkWinnerDialog() {
        String winnerUsername = null;
        int coins = 0;
        int user1Coins = pkInvitation.senderCoins;
        int user2Coins = pkInvitation.receiverCoins;

        if (user1Coins > user2Coins) {
            winnerUsername = pkInvitation.senderName;
            coins = user1Coins;
        } else if (user2Coins > user1Coins) {
            winnerUsername = pkInvitation.receiverName;
            coins = user2Coins;
        }


        if (winnerUsername != null) {
            Dialog dialog = new Dialog(MulticastStreamerActivity.this);
            dialog.setCancelable(true);
            dialog.setContentView(R.layout.item_pk_winner_dialog);
            dialog.getWindow().setBackgroundDrawable(getDrawable(R.drawable.d_round_white_background));

            final TextView usernametxt = dialog.findViewById(R.id.usernametxt);
            usernametxt.setText(winnerUsername);

            final TextView cointxt = dialog.findViewById(R.id.coinTxt);
            cointxt.setText("" + coins);


            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
                    removePkBattle();
                }
            });
            dialog.show();
        } else {
            removePkBattle();
        }

    }

    private void showWinningGif() {

        int user1Coins = pkInvitation.senderCoins;
        int user2Coins = pkInvitation.receiverCoins;

        String winningSide = "0";

        if (user1Coins > user2Coins) {
            if (pkInvitation.senderId.equalsIgnoreCase(Functions.getSharedPreference(this).getString(Variables.U_ID, ""))) {
                winningSide = "1";
            } else {
                winningSide = "2";
            }
        } else if (user2Coins > user1Coins) {
            if (pkInvitation.receiverId.equalsIgnoreCase(Functions.getSharedPreference(this).getString(Variables.U_ID, ""))) {
                winningSide = "1";
            } else {
                winningSide = "2";
            }
        }

        if (winningSide.equals("1")) {

            binding.winningLayout.setVisibility(View.VISIBLE);
            ImageRequest request = ImageRequestBuilder.newBuilderWithResourceId(R.raw.ic_winning_stars)
                    .build();
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(request)
                    .setOldController(binding.winningGif1.getController())
                    .setAutoPlayAnimations(true)
                    .build();

            binding.winningGif1.setController(controller);
        } else if (winningSide.equals("2")) {

            binding.winningLayout.setVisibility(View.VISIBLE);

            ImageRequest request = ImageRequestBuilder.newBuilderWithResourceId(R.raw.ic_winning_stars)
                    .build();
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(request)
                    .setOldController(binding.winningGif2.getController())
                    .setAutoPlayAnimations(true)
                    .build();

            binding.winningGif2.setController(controller);
        }

        if (winningHandler != null && winningRunnable != null) {
            winningHandler.removeCallbacks(winningRunnable);
        }

        winningHandler = new Handler(Looper.getMainLooper());
        winningRunnable = new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            binding.winningLayout.setVisibility(View.GONE);
                            showPkWinnerDialog();

                        } catch (Exception e) {
                        }
                    }
                });

            }
        };
        winningHandler.postDelayed(winningRunnable, 5000);
    }

    private void updateJoinInvitationStatus() {
        HashMap<String, Object> mapData = new HashMap<>();
        if (streamerLiveModel != null) {
            if (streamerLiveModel.isStreamJoinAllow) {
                mapData.put("streamJoinAllow", false);
            } else {
                mapData.put("streamJoinAllow", true);
            }

            Functions.showLoader(this, false, false);
            rootref.child("LiveStreamingUsers").child(streamerLiveModel.getStreamingId()).updateChildren(mapData).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (task.isComplete()) {
                                Functions.cancelLoader();
                            }
                        }
                    });
                }
            });

        }
    }

    private void inviteFriendsForStream() {
        InviteContactsToStreamFragment f = new InviteContactsToStreamFragment(streamingId, "multiple", new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle.getBoolean("isShow", false)) {

                }
            }
        });
        f.show(getSupportFragmentManager(), "InviteContactsToStreamF");
    }

    private void sendComment() {
        EditTextSheetFragment fragment = new EditTextSheetFragment("OwnComment", taggedUserList, new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle.getBoolean("isShow", false)) {
                    if (bundle.getString("action").equals("sendComment")) {
                        taggedUserList = (ArrayList<UserModel>) bundle.getSerializable("taggedUserList");
                        String message = bundle.getString("message");
                        addMessages("comment", message);
                    }
                }
            }
        });
        Bundle bundle = new Bundle();
        bundle.putString("replyStr", "");
        fragment.setArguments(bundle);
        fragment.show(getSupportFragmentManager(), "EditTextSheetF");
    }

    public void ShowDailogForJoinBroadcast() {
        final Dialog alertDialog = new Dialog(MulticastStreamerActivity.this);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.setContentView(R.layout.live_join_broadcast_view);
        alertDialog.getWindow().setBackgroundDrawable(ContextCompat.getDrawable(MulticastStreamerActivity.this, R.drawable.d_round_white_background));

        ImageView swith_camera_btn = alertDialog.findViewById(R.id.swith_camera_btn);
        ImageView live_btn_mute_audio = alertDialog.findViewById(R.id.live_btn_mute_audio);
        ImageView live_btn_beautification = alertDialog.findViewById(R.id.live_btn_beautification);
        ImageView live_btn_mute_video = alertDialog.findViewById(R.id.live_btn_mute_video);
        RelativeLayout tab_cancel = alertDialog.findViewById(R.id.tab_cancel);
        ImageView closeBtn = alertDialog.findViewById(R.id.closeBtn);
        LinearLayout tabClient = alertDialog.findViewById(R.id.tabClient);
        LinearLayout tabSwitch = alertDialog.findViewById(R.id.tabSwitch);

        if (!(onlineType.equals("oneTwoOne"))) {
            if (userRole != Constants.CLIENT_ROLE_BROADCASTER) {
                tabClient.setVisibility(View.GONE);
                tabSwitch.setVisibility(View.GONE);
            }
        }

        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        live_btn_mute_audio.setActivated(!isAudioActivated);
        live_btn_mute_video.setActivated(!isVideoActivated);
        live_btn_beautification.setActivated(!isbeautyActivated);

//        rtcEngine().setBeautyEffectOptions(live_btn_mute_video.isActivated(),
//                com.qboxus.tictic.activitesfragments.livestreaming.Constants.DEFAULT_BEAUTY_OPTIONS);

        tab_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                onBackPressed();
            }
        });
        swith_camera_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                rtcEngine().switchCamera();
            }
        });
        live_btn_mute_audio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                isAudioActivated = live_btn_mute_video.isActivated();
                if (!isAudioActivated) return;
                rtcEngine().muteLocalAudioStream(isAudioActivated);
                view.setActivated(!isAudioActivated);
            }
        });
        live_btn_beautification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                isbeautyActivated = view.isActivated();
                view.setActivated(!isbeautyActivated);
            }
        });
        live_btn_mute_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
                isVideoActivated = view.isActivated();
                if (isVideoActivated) {
                    stopBroadcast();
                } else {
                    startBroadcast();
                }
                view.setActivated(!isVideoActivated);
            }
        });
        alertDialog.show();
    }

    private void addStreamInternetConnection() {
        if (connectCheckListener == null) {
            connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");

            connectCheckListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    boolean connected = snapshot.getValue(Boolean.class);
                    if (connected) {
                        Log.d(com.qboxus.tictic.Constants.tag, "connected");
                        timer.cancel();
                    } else {
                        Log.d(com.qboxus.tictic.Constants.tag, "not connected");
                        timer.cancel();
                        timer = new Timer();
                        timer.schedule(
                                new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                onBackPressed();
                                            }
                                        });
                                    }
                                },
                                DELAY
                        );

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Log.w(com.qboxus.tictic.Constants.tag, "Listener was cancelled");
                }
            };
            connectedRef.addValueEventListener(connectCheckListener);
        }

    }

    public void removeStreamInternetConnection() {
        if (connectedRef != null && connectCheckListener != null) {
            connectedRef.removeEventListener(connectCheckListener);
        }
    }

    public void ShowGiftAnimation(LiveCommentModel item) {

        Functions.printLog(com.qboxus.tictic.Constants.tag, "ShowGiftAnimation(LiveCommentModel item)");

        ivGiftProfile = findViewById(R.id.ivGiftProfile);
        tabGiftTitle = findViewById(R.id.tabGiftTitle);
        tabGiftMain = findViewById(R.id.tabGiftMain);
        animationResetAnimation = findViewById(R.id.animationResetAnimation);
        tvGiftTitle = findViewById(R.id.tvGiftTitle);
        tvGiftCountTitle = findViewById(R.id.tvGiftCountTitle);
        ivGiftItem = findViewById(R.id.ivGiftItem);
        tvSendGiftCount = findViewById(R.id.tvSendGiftCount);
        animationGiftCapture = findViewById(R.id.animationGiftCapture);

        String[] str = item.getComment().split("=====");

        Uri imageUri = Uri.parse(str[2]);

        ivGiftProfile.setController(Functions.frescoImageLoad(item.getUserPicture(), ivGiftProfile, false));

        ivGiftItem.setController(Functions.frescoImageLoad("" + imageUri, ivGiftItem, false));
        tvGiftTitle.setText(item.getUserName());
        tvGiftCountTitle.setText(getString(R.string.gave_you_a) + " " + str[1]);
        tvSendGiftCount.setText("X " + str[0]);

        tabGiftMain.animate().alpha(1).translationX(animationGiftCapture.getX()).setDuration(3000).setListener(
                new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        tabGiftMain.animate().translationY(binding.animationCapture.getY()).setDuration(1000).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                tabGiftMain.clearAnimation();
                                tabGiftMain.animate().alpha(0).translationY(animationResetAnimation.getY()).translationX(animationResetAnimation.getX()).setListener(new AnimatorListenerAdapter() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        super.onAnimationEnd(animation);
                                        tabGiftMain.clearAnimation();
                                    }
                                }).start();
                            }
                        }).start();
                    }


                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        PlayGiftSound();
                    }
                }).start();

        Functions.printLog(com.qboxus.tictic.Constants.tag, " downloadGif(str[2],)");

        if (str[2] != null && str[2].contains(".gif")) {
            showGiftAnimation(str[2], item);
        }

    }

    public void showGiftAnimation(String gifUrl, LiveCommentModel item) {
        Functions.printLog(com.qboxus.tictic.Constants.tag, "showGiftAnimation");
        binding.pkgiftGif.setVisibility(View.VISIBLE);
        ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(
                    String id,
                    @Nullable ImageInfo imageInfo,
                    @Nullable Animatable anim) {
                if (anim != null) {

                    Functions.printLog(com.qboxus.tictic.Constants.tag, "onFinalImageSet");
                    if (item.getSound() != null && !item.getSound().equals("")) {
                        downloadSound(anim, item);
                    } else {
                        startAnimation(anim, item.getTime());
                    }

                } else {
                    Functions.printLog(com.qboxus.tictic.Constants.tag, "onFinalImageSet anim null");
                }
            }
        };

        ImageRequest request = ImageRequest.fromUri(gifUrl);

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setAutoPlayAnimations(true)
                .setOldController(binding.pkgiftGif.getController())
                .setControllerListener(controllerListener)
                .build();

        binding.pkgiftGif.setController(controller);


    }

    public void downloadSound(Animatable anim, LiveCommentModel item) {
        Functions.printLog(com.qboxus.tictic.Constants.tag, "soundUrl" + item.getSound());
        File file = new File(FileUtils.getAppFolder(this) + Variables.APP_HIDED_FOLDER + Variables.gift_sound);
        if (file.exists()) {
            file.delete();
        }

        PRDownloader.initialize(getApplicationContext());
        DownloadRequest prDownloader = PRDownloader.download(item.getSound(), FileUtils.getAppFolder(this) + Variables.APP_HIDED_FOLDER, Variables.gift_sound)
                .build()
                .setOnProgressListener(new OnProgressListener() {
                    @Override
                    public void onProgress(Progress progress) {

                        int prog = (int) ((progress.currentBytes * 100) / progress.totalBytes);
                        Dialogs.showLoadingProgress(prog);

                    }
                });

        prDownloader.start(new OnDownloadListener() {
            @Override
            public void onDownloadComplete() {
                Dialogs.cancelDeterminentLoader();
                Functions.printLog(com.qboxus.tictic.Constants.tag, "onDownloadComplete");

                preparedAudio(anim, item);

            }

            @Override
            public void onError(Error error) {

                Functions.printLog(com.qboxus.tictic.Constants.tag, "Error : " + error.getConnectionException());
                Dialogs.cancelDeterminentLoader();
            }


        });


    }

    public void preparedAudio(Animatable anim, LiveCommentModel item) {
        File file = new File(FileUtils.getAppFolder(this) + Variables.APP_HIDED_FOLDER + Variables.gift_sound);
        if (file.exists()) {
            try {
                audio = new MediaPlayer();
                try {
                    audio.setDataSource(FileUtils.getAppFolder(this) + Variables.APP_HIDED_FOLDER + Variables.gift_sound);
                    player.setVolume(100, 100);
                    audio.prepare();

                    audio.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                startAnimation(anim, item.getTime());

            } catch (Exception e) {
                Log.d(com.qboxus.tictic.Constants.tag, "Exception : " + e);

            }

        }

    }

    public void startAnimation(Animatable anim, String time) {

        Functions.printLog(com.qboxus.tictic.Constants.tag, "Time:" + time);
        int sec = Integer.parseInt(time);
        if (sec == 0) {
            sec = 2;
        }
        int duration = (sec * 1000);
        anim.start();
        new CountDownTimer(duration, 300) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                anim.stop();
                binding.pkgiftGif.setVisibility(View.GONE);
            }
        }.start();
    }

    private void PlayGiftSound() {
        handler = new Handler(Looper.getMainLooper());
        player = MediaPlayer.create(getApplicationContext(), R.raw.gift_tone);
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setVolume(100, 100);
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });
        handler.postDelayed(runnable, 2000);
    }

    public void onTuneStop() {
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }

    // send the comment to the live user
    public void addMessages(String type, String message) {

        final String key = rootref.child("LiveStreamingUsers").child(streamingId).child("Chat").push().getKey();
        String my_id = Functions.getSharedPreference(this).getString(Variables.U_ID, "");
        String my_name = Functions.getSharedPreference(this).getString(Variables.U_NAME, "");
        String my_image = Functions.getSharedPreference(this).getString(Variables.U_PIC, "");

        Date c = Calendar.getInstance().getTime();
        final String formattedDate = Variables.df.format(c);

        LiveCommentModel commentItem = new LiveCommentModel();
        commentItem.setKey(key);
        commentItem.setUserId(my_id);
        commentItem.setUserName(my_name);
        commentItem.setUserPicture(my_image);
        commentItem.setComment(message);
        commentItem.setType(type);
        commentItem.setCommentTime(formattedDate);
        rootref.child("LiveStreamingUsers").child(streamingId).child("Chat").child(key).setValue(commentItem);

    }    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            onTuneStop();
        }
    };

    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        finish();
    }

    // send notification to all of it follower when user live
    public void sendLiveNotification() {

        JSONObject params = new JSONObject();
        try {
            params.put("user_id", Functions.getSharedPreference(this).getString(Variables.U_ID, ""));
            params.put("live_streaming_id",streamingId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        VolleyRequest.JsonPostRequest(MulticastStreamerActivity.this, ApiLinks.sendLiveStreamPushNotfication, params, Functions.getHeaders(context), new Callback() {
            @Override
            public void onResponce(String resp) {
            }
        });

    }

    private void addNodeCameraRequest() {
        if (cameraRequestEventListener == null) {
            cameraRequestEventListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (streamerLiveModel.getDuetConnectedUserId() != null && !(TextUtils.isEmpty(streamerLiveModel.getDuetConnectedUserId()))) {

                                    CameraRequestModel model = snapshot.child(streamerLiveModel.getDuetConnectedUserId()).getValue(CameraRequestModel.class);
                                    if (model.getRequestState().equals("1")) {
                                        binding.ivVideoRequest.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_camera_request_r));
                                        binding.ivVideoRequest.setVisibility(View.VISIBLE);

                                        if (streamerLiveModel.getDuetConnectedUserId() != null
                                                && !(TextUtils.isEmpty(streamerLiveModel.getDuetConnectedUserId()))) {
                                            showCameraRequest(streamerLiveModel.getDuetConnectedUserId());
                                        } else {
                                            Toast.makeText(context, context.getString(R.string.no_user_connected), Toast.LENGTH_SHORT).show();
                                        }
                                    } else if (model.getRequestState().equals("2")) {
                                        binding.ivVideoRequest.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_camera_request_a));
                                        binding.ivVideoRequest.setVisibility(View.VISIBLE);
                                    } else {
                                        binding.ivVideoRequest.setVisibility(View.GONE);
                                    }

                                }

                            }
                        });
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            };
            rootref.child("LiveStreamingUsers").child(streamingId).child("CameraRequest").addValueEventListener(cameraRequestEventListener);
        }
    }

    private void removeNodeCameraRequest() {
        if (rootref != null && cameraRequestEventListener != null) {
            rootref.child("LiveStreamingUsers").child(streamingId).child("CameraRequest").removeEventListener(cameraRequestEventListener);
            cameraRequestEventListener = null;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                    v.clearFocus();
                    hideKeyboard(v);
                }
            }
        }
        return super.dispatchTouchEvent(event);
    }

    public void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }




}
