package com.team.app.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.team.app.Constant;
import com.team.app.R;
import com.team.app.activities.GameDetailActivity;
import com.team.app.adapter.CricketAdapter;
import com.team.app.models.Cricket;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.team.app.Constant.APP_URL_MAIN;

public class FootballFragment extends Fragment {

    private SpinKitView progress;
    private RecyclerView recyclerView;
    private InterstitialAd mInterstitialAd;
    private List<Object> mRecyclerViewItems;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        View inflate = layoutInflater.inflate(R.layout.fragment_football, viewGroup, false);
        recyclerView = inflate.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        progress = inflate.findViewById(R.id.progress);
        LoadInterstitial(); loadCricketData();
        return inflate;
    }

    private void loadCricketData() {
        String JSON_URL = APP_URL_MAIN + "api.php?match=12";
        JsonArrayRequest request = new JsonArrayRequest(JSON_URL, response -> {
            if(response.length()>0) {
                mRecyclerViewItems = new ArrayList<>();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject menuItemObject = response.getJSONObject(i);
                        String id = menuItemObject.getString("id");
                        String match_id = menuItemObject.getString("match_id");
                        String match_type = menuItemObject.getString("match_type");
                        String match_name = menuItemObject.getString("match_name");
                        String match_status = menuItemObject.getString("match_status");
                        String match_date = menuItemObject.getString("match_date");
                        String match_image = menuItemObject.getString("match_image");
                        String match_image_p = menuItemObject.getString("match_image_p");
                        String match_image_1 = menuItemObject.getString("match_image_one");
                        String match_image_2 = menuItemObject.getString("match_image_two");
                        String match_teamA = menuItemObject.getString("match_teamA");
                        String match_teamB = menuItemObject.getString("match_teamB");
                        String match_place = menuItemObject.getString("match_place");
                        String match_time = menuItemObject.getString("match_time");
                        String match_quiz = menuItemObject.getString("match_quiz");
                        String match_winner = menuItemObject.getString("match_winner");
                        String match_detail = menuItemObject.getString("match_detail");
                        Cricket cricket = new Cricket(id, match_id, match_type, match_status, match_teamA, match_teamB, match_date, match_time,
                                match_place, match_image, match_image_p, match_image_1, match_image_2, match_quiz, match_winner, match_detail, match_name);
                        mRecyclerViewItems.add(cricket);
                    } catch (JSONException exception) {
                        Toast.makeText(requireActivity(),"Error While Fatching Data",Toast.LENGTH_SHORT).show();
                    }
                }
                CricketAdapter adapter = new CricketAdapter(requireContext(), progress, mRecyclerViewItems,onTopicClickListener);
                recyclerView.setAdapter(adapter);
            } else {
                progress.setVisibility(View.GONE);
                Toast.makeText(getContext(),"No Football Match Found",Toast.LENGTH_SHORT).show();
            }
        }, error -> Toast.makeText(requireContext(),"No Valid Response Found",Toast.LENGTH_SHORT).show());
        RequestQueue requestQueue = Volley.newRequestQueue(requireContext());
        requestQueue.add(request);
    }

    private void LoadInterstitial() {
        if(Constant.adShown && !Constant.INTERTIAL_ADS_ID.equals("")) {
            AdRequest adRequest = new AdRequest.Builder().build();
            InterstitialAd.load(requireContext(), Constant.INTERTIAL_ADS_ID, adRequest, new InterstitialAdLoadCallback() {
                @Override
                public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                    super.onAdLoaded(interstitialAd);
                    mInterstitialAd = interstitialAd;
                    mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
                        @Override
                        public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                            super.onAdFailedToShowFullScreenContent(adError);
                            requireContext().startActivity(new Intent(requireContext(),GameDetailActivity.class));
                        }

                        @Override
                        public void onAdDismissedFullScreenContent() {
                            super.onAdDismissedFullScreenContent();
                            LoadInterstitial();
                            requireContext().startActivity(new Intent(requireContext(),GameDetailActivity.class));
                        }
                    });
                }

                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                    super.onAdFailedToLoad(loadAdError);
                    mInterstitialAd = null;
                    LoadInterstitial();
                }
            });
        }
    }

    private final CricketAdapter.OnTopicClickListener onTopicClickListener = new CricketAdapter.OnTopicClickListener() {
        @Override
        public void onTopicClick() {
            if (Constant.adShown && !Constant.INTERTIAL_ADS_ID.equals("")) {
                if (mInterstitialAd != null) {
                    mInterstitialAd.show(FootballFragment.this.requireActivity());
                } else {
                    FootballFragment.this.requireContext().startActivity(new Intent(FootballFragment.this.getContext(), GameDetailActivity.class));
                }
            } else {
                FootballFragment.this.requireContext().startActivity(new Intent(FootballFragment.this.getContext(), GameDetailActivity.class));
            }
        }
    };

}
