package com.makeeasy.dpandstatus;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.makeeasy.dpandstatus.Constant.CATEGORY_NAME;
import static com.makeeasy.dpandstatus.Constant.IMG_DATE;
import static com.makeeasy.dpandstatus.Constant.IMG_LINK;
import static com.makeeasy.dpandstatus.Constant.IMG_TITLE;
import static com.makeeasy.dpandstatus.Constant.NID;
import static com.makeeasy.dpandstatus.Constant.OK;
import static com.makeeasy.dpandstatus.Constant.PHOTOS_URL;
import static com.makeeasy.dpandstatus.Constant.POSTS;
import static com.makeeasy.dpandstatus.Constant.STATUS;
import static com.makeeasy.dpandstatus.Constant.alertBox;
import static com.makeeasy.dpandstatus.MainActivity.categoryList;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
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.nativead.NativeAd;
import com.makeeasy.dpandstatus.adapter.PhotoAdapter;
import com.makeeasy.dpandstatus.model.Photo;
import com.makeeasy.dpandstatus.service.Loading;

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

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

public class MainFragment extends Fragment {

    private int counter;
    private int page = 1;
    private Context context;
    private Loading loading;
    private AdLoader adLoader;
    private List<Object> photoList;
    private PhotoAdapter photoAdapter;
    private SwipeRefreshLayout refreshLayout;
    private static final int NUMBER_OF_ADS = 10;
    private static final String ARG_COUNT = "param1";

    public MainFragment() {

    }

    public static MainFragment newInstance(int counter) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COUNT, counter);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            counter = getArguments().getInt(ARG_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        context = view.getContext();
        RecyclerView recyclerView = view.findViewById(R.id.list);
        refreshLayout = view.findViewById(R.id.swipeContainer);
        loading = new Loading(context);
        photoAdapter = new PhotoAdapter(context,new ArrayList<>());
        recyclerView.setAdapter(photoAdapter);
        refreshLayout.setOnRefreshListener(() -> {
            page = 1;getPhotosData(page);
            loadNativeAds();
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    page = page + 1;getPhotosData(page);
                    loadNativeAds();
                }
            }
        });
        refreshLayout.setRefreshing(true);
        getPhotosData(page);loadNativeAds();
    }

    private void loadNativeAds() {
        List<NativeAd> mNativeAds = new ArrayList<>();
        AdLoader.Builder builder = new AdLoader.Builder(context,getResources().getString(R.string.native_id));
        adLoader = builder.forNativeAd(nativeAd -> {
            mNativeAds.add(nativeAd);
            if (!adLoader.isLoading()) {
                if (mNativeAds.size() <= 0) {
                    return;
                }
                int index = 0;
                int offset = (photoList.size()/mNativeAds.size())+1;
                for (NativeAd ad: mNativeAds) {
                    photoList.add(index, ad);
                    index = index + offset;
                }
            }
        }).withAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                if (!adLoader.isLoading()) {
                    if (mNativeAds.size() <= 0) {
                        return;
                    }
                    int index = 0;
                    int offset = (categoryList.size()/mNativeAds.size())+1;
                    for (NativeAd ad: mNativeAds) {
                        photoList.add(index, ad);
                        index = index + offset;
                    }
                }
            }
        }).build();
        adLoader.loadAds(new AdRequest.Builder().build(),NUMBER_OF_ADS);
    }

    private void getPhotosData(int page) {
        photoList = new ArrayList<>();loading.show();
        String cat = categoryList.get(counter).getId();
        String JSON_URL = PHOTOS_URL + "&id=" + cat + "&page=" + page;
        Volley.newRequestQueue(context).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                if(response.getString(STATUS).equalsIgnoreCase(OK)) {
                    JSONArray data = response.getJSONArray(POSTS);
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject obj = data.getJSONObject(i);
                        photoList.add(new Photo(obj.getString(NID),obj.getString(IMG_TITLE),
                                obj.getString(IMG_LINK),obj.getString(IMG_DATE),obj.getString(CATEGORY_NAME)));
                    }
                    refreshLayout.setRefreshing(false);
                    if(!photoList.isEmpty()) {
                        photoAdapter.addMoreData(photoList);
                    } else {
                        makeText(context,"no data found",LENGTH_SHORT).show();
                    }
                } else {
                    makeText(context,"something went wrong",LENGTH_SHORT).show();
                }
                loading.dismiss();
            } catch (JSONException e) {
                loading.dismiss();
                refreshLayout.setRefreshing(false);
                alertBox(context,e.getMessage());
            }
        }, error -> {
            loading.dismiss();
            refreshLayout.setRefreshing(false);
            alertBox(context,error.getMessage());
        }));
    }
}
