package com.team.app.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.Functions;
import com.team.app.R;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.AdapterStatus;
import com.squareup.picasso.Picasso;

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

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

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

public class AppActivity extends AppCompatActivity {

    private AdView adView;
    private List<App> appList;
    private SpinKitView progress;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app);
        MobileAds.initialize(this, initializationStatus -> {
            Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
            for (String adapterClass : statusMap.keySet()) {
                AdapterStatus status = statusMap.get(adapterClass);
            }
            FrameLayout adContainerView0 = findViewById(R.id.bannerAdView);
            if(Constant.adShown && !Constant.BANNER_ADS_ID.equals("")) {
                adView = new com.google.android.gms.ads.AdView(this);
                adView.setAdUnitId(Constant.BANNER_ADS_ID);
                adContainerView0.addView(adView);
                adView.setAdSize(Functions.getAdSize(this));
                adView.loadAd(new AdRequest.Builder().build());
                adContainerView0.setVisibility(View.VISIBLE);
            }
        });
        View view = findViewById(R.id.tool);
        progress = findViewById(R.id.progress);
        view.findViewById(R.id.back).setOnClickListener(v -> finish());
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recyclerView.setHasFixedSize(false);
        loadAppsData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(adView != null) {
            adView.destroy();
        }
    }

    private void loadAppsData() {
        String JSON_URL = APP_URL_MAIN + "api.php?apps=true";
        JsonArrayRequest request = new JsonArrayRequest(JSON_URL, response -> {
            if(response.length()>0) {
                appList = new ArrayList<>();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject menuItemObject = response.getJSONObject(i);
                        String name = menuItemObject.getString("name");
                        String logo = menuItemObject.getString("logo");
                        String link = menuItemObject.getString("link");
                        String signup = menuItemObject.getString("signup");
                        String refer = menuItemObject.getString("refer");
                        String withdraw = menuItemObject.getString("withdraw");
                        String code = menuItemObject.getString("code");
                        App app = new App(name,logo,link,signup,refer,withdraw,code);
                        appList.add(app);
                    } catch (JSONException exception) {
                        Toast.makeText(this,"Error While Fatching Data",Toast.LENGTH_SHORT).show();
                    }
                }
                progress.setVisibility(View.GONE);
                recyclerView.setAdapter(new AppAdapter(this,appList));
            } else {
                progress.setVisibility(View.GONE);
                Toast.makeText(this,"No News Found",Toast.LENGTH_SHORT).show();
            }
        }, error -> Toast.makeText(this,"No Valid Response Found",Toast.LENGTH_SHORT).show());
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);
    }

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

        private final Context ctx;
        private final List<App> appList;

        private AppAdapter(Context ctx, List<App> appList) {
            this.ctx = ctx;
            this.appList = appList;
        }

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

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            AppView appView = (AppView) holder;
            appView.name.setText(appList.get(position).getName());
            appView.signup.setText(appList.get(position).getSignup());
            appView.withdraw.setText(appList.get(position).getWithdraw());
            appView.code.setText(appList.get(position).getCode());
            String url = APP_URL_MAIN + "images/" + appList.get(position).getLogo();
            Picasso.get().load(url).placeholder(R.mipmap.logo).fit().into(appView.logo);
            appView.install.setOnClickListener(v -> ctx.startActivity(new Intent(Intent.ACTION_VIEW)
                    .setData(Uri.parse(appList.get(position).getLink()))));
        }

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

        private static class AppView extends RecyclerView.ViewHolder {
            private final TextView name;
            private final ImageView logo;
            private final TextView withdraw;
            private final TextView signup;
            private final TextView code;
            private final Button install;
            public AppView(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.name);
                logo = itemView.findViewById(R.id.logo);
                withdraw = itemView.findViewById(R.id.withdraw);
                signup = itemView.findViewById(R.id.signup);
                code = itemView.findViewById(R.id.code);
                install = itemView.findViewById(R.id.install);
            }
        }
    }

    private static class App {

        private final String name;
        private final String logo;
        private final String link;
        private final String signup;
        private final String refer;
        private final String withdraw;
        private final String code;

        public App(String name, String logo, String link, String signup, String refer, String withdraw, String code) {
            this.name = name;
            this.logo = logo;
            this.link = link;
            this.signup = signup;
            this.refer = refer;
            this.withdraw = withdraw;
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public String getLogo() {
            return logo;
        }

        public String getLink() {
            return link;
        }

        public String getSignup() {
            return signup;
        }

        public String getRefer() {
            return refer;
        }

        public String getWithdraw() {
            return withdraw;
        }

        public String getCode() {
            return code;
        }
    }

}