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.NewsActivity;
import com.team.app.adapter.NewsAdapter;
import com.team.app.models.News;
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 NewsFragment 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_news, viewGroup, false);
        recyclerView = inflate.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        progress = inflate.findViewById(R.id.progress);
        LoadInterstitial(); loadNewsData();
        return inflate;
    }

    private void loadNewsData() {
        String JSON_URL = APP_URL_MAIN + "api.php?news=true";
        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 title = menuItemObject.getString("title");
                        String thumb = menuItemObject.getString("thumb");
                        String detail = menuItemObject.getString("detail");
                        String date = menuItemObject.getString("date");
                        News news = new News(id, title, thumb, detail, date);
                        mRecyclerViewItems.add(news);
                    } catch (JSONException exception) {
                        Toast.makeText(getContext(), "Error While Fatching Data", Toast.LENGTH_SHORT).show();
                    }
                }
                NewsAdapter adapter = new NewsAdapter(getContext(), progress, mRecyclerViewItems,onTopicClickListener);
                recyclerView.setAdapter(adapter);
            } else {
                progress.setVisibility(View.GONE);
                Toast.makeText(getContext(), "No News Found", Toast.LENGTH_SHORT).show();
            }
        }, error -> Toast.makeText(getContext(),"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(),NewsActivity.class));
                        }

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

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

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

}
