package com.ElyStudio.leGaou.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.VideoOptions;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.nativead.MediaView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdOptions;
import com.google.android.gms.ads.nativead.NativeAdView;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.activities.AllQuizActivity;
import com.ElyStudio.leGaou.activities.DailyQuizScreen;
import com.ElyStudio.leGaou.activities.InviteEarnScreen;
import com.ElyStudio.leGaou.activities.SupportScreen;
import com.ElyStudio.leGaou.adapter.CategoryAdapter;
import com.ElyStudio.leGaou.adapter.QuizAdapter;
import com.ElyStudio.leGaou.databinding.FragmentHomeBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.Category;
import com.ElyStudio.leGaou.models.DailyQuizData;
import com.ElyStudio.leGaou.models.HomeScreenData;
import com.ElyStudio.leGaou.models.Quiz;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.GridViewSpacing;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;
import com.squareup.picasso.Picasso;

import java.util.Calendar;
import java.util.List;
import java.util.Random;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends Fragment {

    public HomeFragment() {
        // Required empty public constructor
    }

    FragmentHomeBinding binding;
    public static final String TAG = "HOME_FRAGMENT";
    RecyclerView quizRecyclerView;
    BottomSheetDialog congratsBottomSheet;
    Context contextFragment;
    int coins,watchEarnReward;

    String nativeAdId,interstitialAdId,rewardedAdId;
    int adEnabled;
    Calendar calendar;
    String day,month,year,currentDate;
    String backendDate;
    int checkInReward;
    RewardedAd mRewardedAd;

    String userInviteCode;
    String invitedBy;

    BottomSheetDialog errorOccurredBottomSheet,noInternetBottomSheet;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater,container,false);

        MobileAds.initialize(getContextNullSafety(), new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        getHomeScreenData();

        binding.moreQuizButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivityNullSafety(),AllQuizActivity.class);
                intent.putExtra(Constants.categoryId,0);
                intent.putExtra(Constants.userCoins,coins);
                intent.putExtra(Constants.watchEarnReward,watchEarnReward);
                intent.putExtra(Constants.adEnabled,adEnabled);
                intent.putExtra(Constants.nativeAdId,nativeAdId);
                intent.putExtra(Constants.interstitialAdId,interstitialAdId);
                intent.putExtra(Constants.rewardedAdId,rewardedAdId);
                startActivity(intent);

            }
        });

        binding.dailyCheckInBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dailyCheckIn();
            }
        });

        binding.inviteEarnCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivityNullSafety(),InviteEarnScreen.class);
                intent.putExtra(Constants.userInviteCode,userInviteCode);
                intent.putExtra(Constants.invitedBy,invitedBy);
                intent.putExtra(Constants.adEnabled,adEnabled);
                intent.putExtra(Constants.rewardedAdId,rewardedAdId);
                startActivity(intent);
            }
        });

        binding.inviteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(getActivityNullSafety(),InviteEarnScreen.class);
                intent.putExtra(Constants.userInviteCode,userInviteCode);
                intent.putExtra(Constants.invitedBy,invitedBy);
                intent.putExtra(Constants.adEnabled,adEnabled);
                intent.putExtra(Constants.rewardedAdId,rewardedAdId);
                startActivity(intent);
            }
        });

        return binding.getRoot();
    }

    void getHomeScreenData(){

        binding.loader.setVisibility(View.VISIBLE);
        binding.homeQuizLayout.setVisibility(View.GONE);

        Call<HomeScreenData> getHomeScreenDataCall = ApiController.getInstance().getApi().getHomeScreenData(FirebaseAuth.getInstance().getUid());
        if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
        {
            getHomeScreenDataCall.enqueue(new Callback<HomeScreenData>() {
                @Override
                public void onResponse(Call<HomeScreenData> call, Response<HomeScreenData> response) {
                    binding.loader.setVisibility(View.GONE);
                    binding.homeQuizLayout.setVisibility(View.VISIBLE);
                    assert response.body() != null;
                    int statusCode = response.body().getStatusCode();
                    if(statusCode==0)
                    {
                        long timeInMillis = response.body().getTime() * 1000L;
                        Calendar cd = Calendar.getInstance();
                        cd.setTimeInMillis(timeInMillis);
                        String day = String.valueOf(cd.get(Calendar.DAY_OF_MONTH));
                        String month = String.valueOf(cd.get(Calendar.MONTH)+1);
                        String year = String.valueOf(cd.get(Calendar.YEAR));

                        // Getting Data in variables
                        userInviteCode = response.body().getInviteCode();
                        invitedBy = response.body().getInvitedBy();
                        backendDate = day+'/'+month+'/'+year;
                        coins = response.body().getCoins();
                        checkInReward = response.body().getCheckInReward();
                        watchEarnReward = response.body().getWatchEarnReward();
                        nativeAdId = response.body().getNativeAdId();
                        interstitialAdId = response.body().getInterstitialAdId();
                        rewardedAdId = response.body().getRewardedAdId();
                        adEnabled = response.body().getAdEnabled();

                        //Setup RecyclerViews
                        if(response.body().getQuizList() != null)
                        {
                            setQuizRecyclerView(response.body().getQuizList());
                        }
                        if(response.body().getCategoryList() != null)
                        {
                            setCategoryRecyclerView(response.body().getCategoryList());
                        }

                        //Showing User data
                        Picasso.get().load(Constants.ADMIN_PANEL_URL +response.body().getAvatar()).into(binding.userAvatar);
                        binding.userName.setText(response.body().getName());
                        binding.userCoins.setText(String.valueOf(response.body().getCoins()));
                        binding.userLevelName.setText(response.body().getLevelName());
                        Picasso.get().load(Constants.ADMIN_PANEL_URL+response.body().getLevelIcon()).into(binding.userLevelIcon);

                        //Loading Native Ads
                        if(adEnabled == 1)
                        {
                            loadNativeAd(response.body().getNativeAdId(),binding.adOnePlaceholder);
                            loadNativeAd(response.body().getNativeAdId(),binding.adPlaceHolderTwo);
                        }


                        getDailyQuizData();
                        loadRewardedAd(rewardedAdId);

                        SharedPreferences sp = getActivityNullSafety().getSharedPreferences(Constants.appPrefs,Context.MODE_PRIVATE);
                        String lastCheckInDate = sp.getString(Constants.lastCheckInDate,"");

                        if(lastCheckInDate.equals(backendDate))
                        {
                            binding.dailyCheckInBtn.setEnabled(false);
                            binding.dailyCheckInBtn.setText(getContextNullSafety().getResources().getString(R.string.check_in_tomorrow));

                        }

                        //Checking is user level changed
                        if(response.body().getIsLevelChanged() == 1)
                            showLevelCongratsBottomSheet(response.body().getLevelName(),response.body().getLevelGreetings(),response.body().getLevelIcon());

                    }
                    else
                    {
                        QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getResources().getString(R.string.some_error),getResources().getColor(R.color.error));
                        showErrorOccurredBottomSheet();
                    }
                }

                @Override
                public void onFailure(Call<HomeScreenData> call, Throwable t) {
                    Log.d(TAG,"getHomeScreenDataCall failure = "+t.getLocalizedMessage());
                    binding.loader.setVisibility(View.GONE);
                    showErrorOccurredBottomSheet();
                }
            });
        }
        else
        {
            showNoInternetBottomSheet();
        }


    }

    void setQuizRecyclerView(List<Quiz> quizList){

        if(quizList.size()==0)
        {
            binding.quizzeTag.setVisibility(View.GONE);
            binding.moreQuizButton.setVisibility(View.GONE);
        }
        quizRecyclerView = binding.quizRecyclerview;
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),2, RecyclerView.VERTICAL,false);
        QuizAdapter adapter = new QuizAdapter(getContextNullSafety(),quizList,getActivityNullSafety(),binding.getRoot(),coins,watchEarnReward,adEnabled,nativeAdId,interstitialAdId,rewardedAdId);
        quizRecyclerView.addItemDecoration(new GridViewSpacing(2,40,false));
        quizRecyclerView.setLayoutManager(layoutManager);
        quizRecyclerView.setAdapter(adapter);
    }

    void setCategoryRecyclerView(List<Category> categoryList){
        if(categoryList.size() == 0)
        {
            binding.categoriesTag.setVisibility(View.GONE);
        }
        RecyclerView categoryRecyclerView = binding.categoriesRecyclerview;
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(),RecyclerView.HORIZONTAL,false);
        CategoryAdapter adapter = new CategoryAdapter(getContext(),categoryList,adEnabled,coins,watchEarnReward,nativeAdId,interstitialAdId,rewardedAdId);
        categoryRecyclerView.setLayoutManager(layoutManager);
        categoryRecyclerView.setAdapter(adapter);
    }

    void showLevelCongratsBottomSheet(String name,String greetings,String icon){
        Random random = new Random();
        int randomColor = random.nextInt(9);
        int color;

        if(randomColor==1)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_1);
        }
        else if(randomColor ==2)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_2);
        }
        else if(randomColor == 3)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_3);
        }
        else if(randomColor==4)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_4);
        }
        else if(randomColor==5)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_5);
        }
        else if(randomColor==6)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_6);
        }
        else if(randomColor == 7){
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_7);
        }
        else if(randomColor==8)
        {
            color = getContextNullSafety().getResources().getColor(R.color.quiz_color_text_8);
        }
        else
        {
            color = getContextNullSafety().getResources().getColor(R.color.primary);
        }

        congratsBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.level_congrats_bottom_sheet_layout,(ConstraintLayout) getActivityNullSafety().findViewById(R.id.congratsBottomSheetLayout));
        congratsBottomSheet.setContentView(view);
        TextView congratsTitle = congratsBottomSheet.findViewById(R.id.levelCongratsTitle);
        TextView congratsGreetings = congratsBottomSheet.findViewById(R.id.levelGreetings);
        ImageView levelIcon = congratsBottomSheet.findViewById(R.id.congratsLevelIcon);
        Button thanksButton = congratsBottomSheet.findViewById(R.id.thanksButton);
        String title = getContextNullSafety().getResources().getString(R.string.congrats_title)+' '+name;
        congratsTitle.setTextColor(color);
        congratsTitle.setText(title);
        Picasso.get().load(Constants.ADMIN_PANEL_URL+icon).into(levelIcon);
        congratsGreetings.setText(greetings);

        thanksButton.setBackgroundColor(color);
        thanksButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                congratsBottomSheet.cancel();
            }
        });

        if(!getActivityNullSafety().isFinishing())
        {
            congratsBottomSheet.show();
        }

    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextFragment = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
        if (getContext() != null) return getContext();
        if (getActivity() != null) return getActivity();
        if (contextFragment != null) return contextFragment;
        if (getView() != null && getView().getContext() != null) return getView().getContext();
        if (requireContext() != null) return requireContext();
        if (requireActivity() != null) return requireActivity();
        if (requireView() != null && requireView().getContext() != null)
            return requireView().getContext();

        return null;
    }

    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }

    public void populateNativeAdView(NativeAd nativeAd, NativeAdView nativeAdView){

        nativeAdView.setMediaView((MediaView) nativeAdView.findViewById(R.id.adMedia));
        nativeAdView.setIconView(nativeAdView.findViewById(R.id.adIcon));
        nativeAdView.setHeadlineView(nativeAdView.findViewById(R.id.adHeadline));
        nativeAdView.setAdvertiserView(nativeAdView.findViewById(R.id.advertiser));
        nativeAdView.setStarRatingView(nativeAdView.findViewById(R.id.adStar));
        nativeAdView.setBodyView(nativeAdView.findViewById(R.id.adBody));
        nativeAdView.setPriceView(nativeAdView.findViewById(R.id.adPrice));
        nativeAdView.setStoreView(nativeAdView.findViewById(R.id.adStore));
        nativeAdView.setCallToActionView(nativeAdView.findViewById(R.id.callToActionButton));

        if(nativeAd!= null) {

            ((TextView) nativeAdView.getHeadlineView()).setText(nativeAd.getHeadline());
            nativeAdView.getMediaView().setMediaContent(nativeAd.getMediaContent());

            if(nativeAd.getBody() == null)
            {
                nativeAdView.getBodyView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getBodyView().setVisibility(View.VISIBLE);
                ((TextView) nativeAdView.getBodyView()).setText(nativeAd.getBody());
            }

            if(nativeAd.getAdvertiser() == null)
            {
                nativeAdView.getAdvertiserView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getAdvertiserView().setVisibility(View.VISIBLE);
                ((TextView) nativeAdView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
            }

            if(nativeAd.getStarRating() == null)
            {
                nativeAdView.getStarRatingView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getStarRatingView().setVisibility(View.VISIBLE);
                ((RatingBar) nativeAdView.getStarRatingView()).setRating(nativeAd.getStarRating().floatValue());
            }

            if(nativeAd.getIcon() == null)
            {
                nativeAdView.getIconView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getIconView().setVisibility(View.VISIBLE);
                ((ImageView) nativeAdView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
            }

            if(nativeAd.getPrice() == null)
            {
                nativeAdView.getPriceView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getPriceView().setVisibility(View.VISIBLE);
                ((TextView) nativeAdView.getPriceView()).setText(nativeAd.getPrice());
            }

            if(nativeAd.getStore() == null)
            {
                nativeAdView.getStoreView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getStoreView().setVisibility(View.VISIBLE);
                ((TextView) nativeAdView.getStoreView()).setText(nativeAd.getStore());
            }

            if(nativeAd.getCallToAction() == null)
            {
                nativeAdView.getCallToActionView().setVisibility(View.INVISIBLE);
            }
            else
            {
                nativeAdView.getCallToActionView().setVisibility(View.VISIBLE);
                ((Button) nativeAdView.getCallToActionView()).setText(nativeAd.getCallToAction());
            }

            nativeAdView.setNativeAd(nativeAd);

        }
    }

    public void loadNativeAd(String adId,FrameLayout frameLayout){

        AdLoader.Builder builder = new AdLoader.Builder(getContextNullSafety(),adId);

        builder.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
            @Override
            public void onNativeAdLoaded(@NonNull NativeAd nativeAd) {

                NativeAdView nativeAdView = (NativeAdView) getActivityNullSafety().getLayoutInflater().inflate(R.layout.big_native_ad_design,null);

                populateNativeAdView(nativeAd,nativeAdView);
                frameLayout.removeAllViews();
                frameLayout.addView(nativeAdView);
            }
        });

        VideoOptions videoOptions =
                new VideoOptions.Builder().setStartMuted(true).build();

        NativeAdOptions adOptions =
                new NativeAdOptions.Builder().setVideoOptions(videoOptions).build();

        builder.withNativeAdOptions(adOptions);

        AdLoader adLoader = builder.withAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                Log.d(TAG,"Failed to native ad = "+loadAdError.getMessage());
            }
        }).build();

        adLoader.loadAd(new AdRequest.Builder().build());


    }

    private void getDailyQuizData(){

        calendar = Calendar.getInstance();
        day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        month = String.valueOf(calendar.get(Calendar.MONTH)+1);
        year = String.valueOf(calendar.get(Calendar.YEAR));
        currentDate = day+'/'+month+'/'+year;

        SharedPreferences sharedPreferences = getActivityNullSafety().getSharedPreferences(Constants.appPrefs,Context.MODE_PRIVATE);
        String lastPlayedDate = sharedPreferences.getString(Constants.isDailyQuizPlayed,"");
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if(lastPlayedDate.equals(backendDate))
        {
            binding.playDailyQuizBtn.setText(getContextNullSafety().getResources().getString(R.string.play_tomorrow));
            binding.playDailyQuizBtn.setEnabled(false);
        }
        else
        {
            Call<DailyQuizData> getDailyQuizData = ApiController.getInstance().getApi().getDailyQuizData();

            getDailyQuizData.enqueue(new Callback<DailyQuizData>() {
                @Override
                public void onResponse(Call<DailyQuizData> call, Response<DailyQuizData> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        if(response.body().getDailyQuizQuestions() == null || response.body().getDailyQuizQuestions().size() == 0)
                        {
                            binding.dailyQuizCard.setVisibility(View.INVISIBLE);
                        }
                        else
                        {
                            binding.playDailyQuizBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    editor.putString(Constants.isDailyQuizPlayed,currentDate);
                                    editor.apply();
                                    startDailyQuiz(getContextNullSafety().getResources().getString(R.string.daily_quiz),response.body().getEntryFee(),response.body().getLivesAvailable(),response.body().getQuestionLimit(),response.body().getPrize(),response.body().getTime());
                                }
                            });
                        }
                    }
                }

                @Override
                public void onFailure(Call<DailyQuizData> call, Throwable t) {
                    Log.d(TAG,"getDailyQuizDataCallFailure = "+t.getLocalizedMessage());
                }
            });
        }

    }

    public void startDailyQuiz(String quizName,int quizEntryFee,int livesAvailable,int questionLimit,float prizePerQuestion,int time){
        Intent intent = new Intent(getContextNullSafety(), DailyQuizScreen.class);

        intent.putExtra(Constants.quizName,quizName);
        intent.putExtra(Constants.quizEntryFee,quizEntryFee);

        intent.putExtra(Constants.quizQuestionLimit,questionLimit);
        intent.putExtra(Constants.quizLivesAvailable, livesAvailable);
        intent.putExtra(Constants.quizTimeAvailable, time);
        intent.putExtra(Constants.quizPrizePerQuestion,prizePerQuestion);

        intent.putExtra(Constants.adEnabled,adEnabled);
        intent.putExtra(Constants.nativeAdId,nativeAdId);
        intent.putExtra(Constants.interstitialAdId,interstitialAdId);
        intent.putExtra(Constants.rewardedAdId,rewardedAdId);

        getContextNullSafety().startActivity(intent);
    }

    public void dailyCheckIn(){

        SharedPreferences preferences = getActivityNullSafety().getSharedPreferences(Constants.appPrefs,Context.MODE_PRIVATE);
        String lastCheckIn = preferences.getString(Constants.lastCheckInDate,"");
        SharedPreferences.Editor editor = preferences.edit();

        if(lastCheckIn.equals(backendDate))
        {
            binding.dailyCheckInBtn.setEnabled(false);
            binding.dailyCheckInBtn.setText(getResources().getString(R.string.check_in_tomorrow));
        }
        else
        {
            editor.putString(Constants.lastCheckInDate,backendDate).apply();
            Call<ApiResponse> addCheckInCoinsCall = ApiController.getInstance().getApi().addCoins(FirebaseAuth.getInstance().getUid(), checkInReward,"DAIlY CHECK IN",getActivityNullSafety().getResources().getString(R.string.daily_check_in_playing_history));

            addCheckInCoinsCall.enqueue(new Callback<ApiResponse>() {
                @Override
                public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        if(mRewardedAd != null)
                        {
                            mRewardedAd.show(getActivityNullSafety(), new OnUserEarnedRewardListener() {
                                @Override
                                public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                                    QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getResources().getString(R.string.check_in_success),getContextNullSafety().getResources().getColor(R.color.success));
                                    binding.dailyCheckInBtn.setEnabled(false);
                                    binding.dailyCheckInBtn.setText(getResources().getString(R.string.check_in_tomorrow));
                                }
                            });
                        }
                        else
                        {
                            QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getResources().getString(R.string.check_in_success),getContextNullSafety().getResources().getColor(R.color.success));
                            binding.dailyCheckInBtn.setEnabled(false);
                            binding.dailyCheckInBtn.setText(getResources().getString(R.string.check_in_tomorrow));
                        }
                    }
                    else
                    {
                        QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getContextNullSafety().getResources().getString(R.string.internal_error),getContextNullSafety().getResources().getColor(R.color.error));
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse> call, Throwable t) {
                    Log.d(TAG,"addCheckInCoinsCall Failure = "+t.getLocalizedMessage());
                    QuizzeSnackBar.showSnackBar(getContextNullSafety(),binding.getRoot(),getContextNullSafety().getResources().getString(R.string.some_error_occurred),getContextNullSafety().getResources().getColor(R.color.error));

                }
            });
        }

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().findViewById(R.id.errorOccurredBottomSheetLayout),false);
        errorOccurredBottomSheet.setContentView(view);
        errorOccurredBottomSheet.setCancelable(false);
        Button contactSupportBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = errorOccurredBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = errorOccurredBottomSheet.findViewById(R.id.bottomSheetTitle);
        TextView bottomSheetSubText = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSubText);

        bottomSheetTitle.setText(getActivityNullSafety().getResources().getString(R.string.some_error_occurred));
        bottomSheetSubText.setText(getActivityNullSafety().getResources().getString(R.string.error_subtext));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.error_illustration));
        contactSupportBtn.setText(getActivityNullSafety().getResources().getString(R.string.contact_support));
        tryAgainBtn.setText(getActivityNullSafety().getResources().getString(R.string.try_again));

        contactSupportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivityNullSafety(), SupportScreen.class));
            }
        });

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                errorOccurredBottomSheet.cancel();
                getHomeScreenData();
            }
        });

        if(!getActivityNullSafety().isFinishing())
        {
            errorOccurredBottomSheet.show();
        }
    }

    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().findViewById(R.id.errorOccurredBottomSheetLayout),false);
        noInternetBottomSheet.setContentView(view);

        Button contactSupportBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = noInternetBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = noInternetBottomSheet.findViewById(R.id.bottomSheetTitle);
        noInternetBottomSheet.setCancelable(false);
        TextView bottomSheetSubText = noInternetBottomSheet.findViewById(R.id.bottomSheetSubText);
        contactSupportBtn.setVisibility(View.GONE);

        tryAgainBtn.setText(getContextNullSafety().getResources().getString(R.string.try_again));

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
                {
                    getHomeScreenData();
                    noInternetBottomSheet.cancel();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(getContextNullSafety(),view,getResources().getString(R.string.no_internet),getResources().getColor(R.color.error));
                }
            }
        });

        bottomSheetTitle.setText(getContextNullSafety().getResources().getString(R.string.no_internet));
        bottomSheetSubText.setText(getContextNullSafety().getResources().getString(R.string.no_internet_sub_text));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.no_conection_illustration));

        if(!getActivityNullSafety().isFinishing())
        {
            noInternetBottomSheet.show();
        }

    }

    private void loadRewardedAd(String adId){

        if(adEnabled == 1)
        {
            AdRequest adRequest = new AdRequest.Builder().build();

            RewardedAd.load(getContextNullSafety(), adId, adRequest, new RewardedAdLoadCallback() {
                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    super.onAdFailedToLoad(loadAdError);
                    Log.d(TAG,"Failed to load rewarded ad = "+loadAdError);
                    mRewardedAd = null;
                }

                @Override
                public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                    super.onAdLoaded(rewardedAd);
                    mRewardedAd = rewardedAd;
                }
            });
        }

    }
}