package com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.ads.MaxAdView;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.applovin.sdk.AppLovinSdk;
import com.facebook.ads.AudienceNetworkAds;
import com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.Constant;
import com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.R;

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

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

public class MainActivity extends AppCompatActivity {

    private ProgressBar progress;
    private List<Category> categoryList;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        AudienceNetworkAds.initialize(this);
        AppLovinSdk.getInstance( this ).setMediationProvider("max");
        AppLovinSdk.initializeSdk( this, configuration -> {
            MaxAdView maxAdView = new MaxAdView(getString(R.string.banner_id),this);
            ((LinearLayout)findViewById(R.id.adView)).addView(maxAdView);
            maxAdView.loadAd();
        });
        progress = findViewById(R.id.progress);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this,2));
        recyclerView.setHasFixedSize(true);
        Volley.newRequestQueue(this).add(new JsonArrayRequest(Constant.CATEGORY_URL, response -> {
            if (response.length() > 0) {
                categoryList = new ArrayList<>();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject data = response.getJSONObject(i);
                        categoryList.add(new Category(data.getString("id"),data.getString("category")));
                    } catch (JSONException e) {
                        Toast.makeText(MainActivity.this,"Error While Fatching Data",Toast.LENGTH_SHORT).show();
                    }
                }
                categoryList.add(new Category("999", "Help & Support"));
                recyclerView.setAdapter(new CategoryAdapter(MainActivity.this, categoryList));
                progress.setVisibility(View.GONE);
            }
        }, error -> {
            progress.setVisibility(View.GONE);
            Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
        }));
    }

    private static class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final Context ctx;
        private MaxInterstitialAd mAd;
        private final List<Category> itemList;

        CategoryAdapter(Context ctx,List<Category> itemList) {
            this.ctx = ctx;
            this.itemList = itemList;
            loadInterstitialAd(ctx);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(ctx).inflate(R.layout.item,parent,false);
            return new CategoryView(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            CategoryView categoryView = (CategoryView) holder;
            categoryView.categoryName.setText(itemList.get(position).getName());
            categoryView.itemView.setOnClickListener(view -> {
                if(mAd.isReady()) {
                    mAd.showAd();
                }
                if(itemList.get(position).getId().equals("999")) {
                    Constant.sendMail(ctx);
                } else {
                    LoanListActivity.category = itemList.get(position);
                    ctx.startActivity(new Intent(ctx, LoanListActivity.class));
                }
            });
        }

        @Override
        public int getItemCount() {
            return itemList.size();
        }

        private static class CategoryView extends RecyclerView.ViewHolder{
            private final TextView categoryName;
            public CategoryView(@NonNull View itemView) {
                super(itemView);
                categoryName = itemView.findViewById(R.id.txt);
            }
        }

        private void loadInterstitialAd(Context ctx) {
            mAd = new MaxInterstitialAd(ctx.getString(R.string.interstitial_id), (Activity) ctx);
            mAd.setListener(new MaxAdListener() {
                @Override
                public void onAdLoaded(MaxAd ad) {

                }

                @Override
                public void onAdDisplayed(MaxAd ad) {

                }

                @Override
                public void onAdHidden(MaxAd ad) {
                    loadInterstitialAd(ctx);
                }

                @Override
                public void onAdClicked(MaxAd ad) {

                }

                @Override
                public void onAdLoadFailed(String adUnitId, MaxError error) {
                    loadInterstitialAd(ctx);
                }

                @Override
                public void onAdDisplayFailed(MaxAd ad, MaxError error) {

                }
            });
            mAd.loadAd();
        }
    }

    public static class Category {
        private final String id;
        private final String name;
        public Category(String id, String name) {
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public String getName() {
            return name;
        }
    }
}
