package com.qboxus.tictic.activitesfragments.livestreaming.activities;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
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.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.volley.plus.VPackages.VolleyRequest;
import com.volley.plus.interfaces.Callback;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import com.qboxus.tictic.R;
import com.qboxus.tictic.activitesfragments.EditTextSheetF;
import com.qboxus.tictic.activitesfragments.livestreaming.adapter.LiveCommentsAdapter;
import com.qboxus.tictic.activitesfragments.livestreaming.adapter.LiveUserViewAdapter;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.InviteContactsToStreamF;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.PkBattleInviteF;
import com.qboxus.tictic.activitesfragments.livestreaming.fragments.PkBattleInviteSendF;
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.analytics.DateOperations;
import com.qboxus.tictic.activitesfragments.shoping.ShopItemDetailA;
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.StreamJoinModel;
import com.qboxus.tictic.models.StreamShowHeartModel;
import com.qboxus.tictic.models.UsersModel;
import com.qboxus.tictic.simpleclasses.Functions;
import com.qboxus.tictic.simpleclasses.OnSwipeTouchListener;
import com.qboxus.tictic.simpleclasses.Variables;
import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.video.VideoEncoderConfiguration;
import io.paperdb.Paper;


public class MulticastStreamerA extends RtcBaseActivity implements View.OnClickListener {

    private VideoEncoderConfiguration.VideoDimensions mVideoDimension;
    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;

    ArrayList<ProductModel> pList=new ArrayList<>();
    ActivityMulticastStreamerBinding binding;
    
    @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(MulticastStreamerA.this,
                R.layout.activity_multicast_streamer);

        context=MulticastStreamerA.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");
            description=bundle.getStringExtra("description");
            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();
        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() {
        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.startpkBtn.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);


    }



    // initailze the adapter
    ArrayList<LiveCommentModel> dataList=new ArrayList<>();
    RecyclerView recyclerView;
    LiveCommentsAdapter adapter;
    public void initCommentAdapter() {
        dataList.clear();
        recyclerView = (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 (itemUpdate.getType().equals("shareStream"))
                {
                    inviteFriendsForStream();
                }
                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());
                    }

                }
            }
        });
        recyclerView.setAdapter(adapter);

    }






    ValueEventListener productChildListener;
    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;
        }
    }

    // initailze the adapter
    ArrayList<ProductModel> productsList=new ArrayList<>();
    StreamingProductsAdapter productsAdapter;
    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) {
                ProductModel model=(ProductModel) object;
                Intent intent=new Intent(MulticastStreamerA.this, ShopItemDetailA.class);
                intent.putExtra("data", (Serializable) model);
                startActivity(intent);
            }
        });
        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();
                            }
                        }
                    });
                }
            }
        });


    }


    ChildEventListener commentChildListener;
    Calendar current_cal;
    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 (Functions.checkTimeDiffernce(current_cal,model.getCommentTime()))
                    {
                        if(model.getType().equalsIgnoreCase("gift"))
                        {
                           MulticastStreamerA.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) {

            }
        });
        binding.liveUserViewRecyclerView.setAdapter(liveUserViewAdapter);
    }


    ArrayList<StreamJoinModel> jointUserList=new ArrayList<>();
    ValueEventListener joinValueEventListener;
    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;
        }
    }


    ChildEventListener likeValueEventListener;
    int heartCounter=0;
    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);
                       MulticastStreamerA.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);

        }
    }




    ValueEventListener coinValueEventListener;
    ArrayList<LiveCoinsModel> senderCoinsList=new ArrayList<>();
    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=true;
        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.getSenderId().equals(""+uid) || pkInvitation.getReceiverId().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,""+Functions.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;

        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();
        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.setDualStreaming(dualStreaming);
        if (dualStreaming)
        {
            model.setStreamJoinAllow(true);
        }
        else
        {
            model.setStreamJoinAllow(false);
        }
        model.setJoinStreamPrice(""+joinStreamPrice);
        model.setUserCoins("0");
        model.setIsVerified(""+Functions.getSharedPreference(MulticastStreamerA.this).getString(Variables.IS_VERIFIED,"0"));
        model.setDuetConnectedUserId("");
        model.setStreamUid(-1);
        model.setProductsList(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.getSenderStreamingId()).child("pkInvitation").removeValue();
            rootref.child("LiveStreamingUsers").child(pkInvitation.getReceiverStreamingId()).child("pkInvitation").removeValue();
        }

        rootref.child("LiveStreamingUsers").child(streamingId).removeValue();
    }

    // check the current live user status eighter user is live or not when users goes offline this callback will hit
    ValueEventListener broadcastValueEventListener;
    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(MulticastStreamerA.this).edit()
                                    .putString(Variables.U_WALLET, ""+streamerLiveModel.getUserCoins()).commit();
                        }
                    });
                }
                else
                {
                    MulticastStreamerA.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.tabEffects:
            {
                performBeautify();
            }
            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;

            case R.id.startpkBtn:
                break;
        }
    }






    public PkInvitation pkInvitation;
    ValueEventListener pkInvitationListener;
    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.getAction()!=null && pkInvitation.getAction().equals("1")) {

                            if(!config().getChannelName().equalsIgnoreCase(pkInvitation.getPkStreamingId())) {
                                acceptPkBattleInvitation();
                                hideInvitationViews();
                            }

                            if(userId.equalsIgnoreCase(pkInvitation.getSenderId())) {
                                binding.coinCount1Txt.setText(""+pkInvitation.getSenderCoins());
                                binding.coinCount2Txt.setText(""+pkInvitation.getReceiverCoins());
                            }

                            if(userId.equalsIgnoreCase(pkInvitation.getReceiverId())) {
                                binding.coinCount1Txt.setText(""+pkInvitation.getReceiverCoins());
                                binding.coinCount2Txt.setText(""+pkInvitation.getSenderCoins());
                            }

                            updatePkBar();

                        }

                        else if (pkInvitation.getReceiverId()!=null && pkInvitation.getReceiverId().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.getSenderId())){
            int user1Coins=pkInvitation.getSenderCoins();
            int user2Coins=pkInvitation.getReceiverCoins();

            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.getReceiverId())){
            int user1Coins=pkInvitation.getReceiverCoins();
            int user2Coins=pkInvitation.getSenderCoins();

            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(){
        PkBattleInviteF f = PkBattleInviteF.newInstance( new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if(bundle!=null){

                    LiveUserModel liveUserModel = (LiveUserModel) bundle.getSerializable("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(MulticastStreamerA.this,"The host is busy now. please try again later!");
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });


                }

            }
        });
        f.show(getSupportFragmentManager(), "PkBattleInviteF");
    }

    PkBattleInviteSendF pkBattleInviteSendF;
    public void openPkBattelInviteSendF(LiveUserModel liveUserModel){
        pkBattleInviteSendF = PkBattleInviteSendF.newInstance(streamingId,liveUserModel,new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
            }
        });
        pkBattleInviteSendF.show(getSupportFragmentManager(), "PkBattleInviteSendF");
    }



    Dialog pkInvitationDialog;
    CountDownTimer pkInvitationTimer;
    public void showPkInvitationDialog()
    {
        pkInvitationDialog = new Dialog(MulticastStreamerA.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.getSenderName() +" 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.getSenderStreamingId()).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.getSenderStreamingId()).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.getSenderStreamingId()+"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.getSenderStreamingId()).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 acceptPkBattleInvitation(){
        rtcEngine().leaveChannel();
        config().setUid(Functions.getSharedPreference(this).getString(Variables.U_ID,""));
        config().setChannelName(pkInvitation.getPkStreamingId());
        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) {
                    // app-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.getSenderId())) {
                    removeRemoteUser(Integer.parseInt(pkInvitation.getReceiverId()));
                } else {
                    removeRemoteUser(Integer.parseInt(pkInvitation.getSenderId()));
                }
            } 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.startpkBtn.setVisibility(View.GONE);
        binding.tabpk.setEnabled(false);
    }


    public void hidePkBattleViews(){
        binding.pkProgressLayout.setVisibility(View.GONE);
        binding.pkbattleTimerLayout.setVisibility(View.GONE);
        binding.tabpk.setEnabled(true);
    }

    CountDownTimer pkBattleCountDown;
    public void startPkCountDown(){
        showPkBattleViews();

        if(pkBattleCountDown==null) {

         //   Calendar calendar=Calendar.getInstance();

            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.getTimeStamp();
                    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) {

                }
            });



        //    long timeDiffernce = com.qboxus.tictic.Constants.PkBattleTime - Functions.getTimeDiffernce(calendar,pkInvitation.getPkStreamingTime());

            //ServerValue.TIMESTAMP

         //   long timeDiffernce = com.qboxus.tictic.Constants.PkBattleTime - 1000000;



        }
    }


    public void stopPkCountDown(){
        if(pkBattleCountDown!=null){
            pkBattleCountDown.cancel();
            pkBattleCountDown=null;
        }
    }


    public void showPkWinnerDialog()
    {
        String winnerUsername=null;
        int coins=0;
            int user1Coins=pkInvitation.getSenderCoins();
            int user2Coins=pkInvitation.getReceiverCoins();

            if(user1Coins>user2Coins){
                winnerUsername=pkInvitation.getSenderName();
                coins=user1Coins;
            }

            else if (user2Coins>user1Coins) {
                winnerUsername=pkInvitation.getReceiverName();
                coins=user2Coins;
            }


            if(winnerUsername!=null) {
                Dialog dialog = new Dialog(MulticastStreamerA.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();
            }

    }


    Handler winningHandler;
    Runnable winningRunnable;
    private void showWinningGif() {

        int user1Coins=pkInvitation.getSenderCoins();
        int user2Coins=pkInvitation.getReceiverCoins();

        String winningSide="0";

        if(user1Coins>user2Coins){
            if(pkInvitation.getSenderId().equalsIgnoreCase(Functions.getSharedPreference(this).getString(Variables.U_ID,""))){
                winningSide="1";
            }else {
                winningSide="2";
            }
        }
        else if (user2Coins>user1Coins) {
            if(pkInvitation.getReceiverId().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 performBeautify() {
        isbeautyActivated=!isbeautyActivated;
        rtcEngine().setBeautyEffectOptions(isbeautyActivated,
                com.qboxus.tictic.activitesfragments.livestreaming.Constants.DEFAULT_BEAUTY_OPTIONS);
    }

    private void updateJoinInvitationStatus() {
        HashMap<String,Object> mapData=new HashMap<>();
        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() {
        InviteContactsToStreamF f = new InviteContactsToStreamF(streamingId,"multiple",new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle.getBoolean("isShow",false))
                {

                }
            }
        });
        f.show(getSupportFragmentManager(), "InviteContactsToStreamF");
    }

    ArrayList<UsersModel> taggedUserList = new ArrayList<>();
    private void sendComment() {
        EditTextSheetF fragment = new EditTextSheetF("OwnComment",taggedUserList, new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle.getBoolean("isShow",false))
                {
                    if (bundle.getString("action").equals("sendComment"))
                    {
                        taggedUserList= (ArrayList<UsersModel>) 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 heartsShow()
    {
        binding.streamLikeView.addHeart(new Random().nextInt(5));
    }


    boolean isAudioActivated=true,isVideoActivated=true,isbeautyActivated=true;
    public void ShowDailogForJoinBroadcast() {
        final Dialog alertDialog = new Dialog(MulticastStreamerA.this);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.setContentView(R.layout.live_join_broadcast_view);
        alertDialog.getWindow().setBackgroundDrawable(ContextCompat.getDrawable(MulticastStreamerA.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);
                performBeautify();
            }
        });
        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();
    }


    ValueEventListener connectCheckListener;
    DatabaseReference connectedRef;
    private Timer timer = new Timer();
    private final long DELAY = 20000;
    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);
        }
    }



    SimpleDraweeView ivGiftProfile,ivGiftItem;
    LinearLayout tabGiftTitle;
    RelativeLayout tabGiftMain;
    View animationGiftCapture,animationResetAnimation;
    TextView tvGiftTitle,tvGiftCountTitle,tvSendGiftCount;
    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(Functions.getAppFolder(this)+Variables.APP_HIDED_FOLDER + Variables.gift_sound);
        if(file.exists()){
            file.delete();
        }

        PRDownloader.initialize(getApplicationContext());
        DownloadRequest prDownloader = PRDownloader.download(item.getSound(),  Functions.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);
                        Functions.showLoadingProgress(prog);

                    }
                });

        prDownloader.start(new OnDownloadListener() {
            @Override
            public void onDownloadComplete() {
                Functions.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());
                Functions.cancelDeterminentLoader();
            }


        });


    }


    MediaPlayer audio;
    public void preparedAudio(Animatable anim,LiveCommentModel item) {
        File file = new File(Functions.getAppFolder(this)+Variables.APP_HIDED_FOLDER + Variables.gift_sound);
        if (file.exists()) {
            try {
                audio = new MediaPlayer();
                try {
                    audio.setDataSource(Functions.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();
    }

    MediaPlayer player;
    Handler handler;
    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);
    }

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            onTuneStop();
        }
    };

    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);

    }




    @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, ""));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        VolleyRequest.JsonPostRequest(MulticastStreamerA.this, ApiLinks.sendLiveStreamPushNotfication,params, Functions.getHeaders(context),new Callback() {
            @Override
            public void onResponce(String resp) {
            }
        });

    }


    ValueEventListener  cameraRequestEventListener;
    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;
        }
    }



}
