package com.friendvilla.shayaristock;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShayariActivity extends AppCompatActivity {

    private String Cat,API_URL;
    private int num = 0;
    private Handler handler;
    private Runnable runnable;
    private boolean run = true;
    private Dialog dialog;
    private RecyclerView recyclerView;
    private List<ItemClass> LIST_ITEMS,LIST_MORE_ITEMS;
    private ItemViewAdapter movieAdapter;
    private InterstitialAd interstitialAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shayari);
        Toolbar toolbar = (Toolbar) findViewById(R.id.stoolbar);
        setSupportActionBar(toolbar);
        Cat = getIntent().getStringExtra("Category");
        assert Cat != null;
        Objects.requireNonNull(getSupportActionBar()).setTitle(Cat.toUpperCase() + " SHAYARI");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                run = false;
                finish();
            }
        });
        switch (Cat) {
            case "attitude":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=1&num=";
                break;
            case "birthday":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=2&num=";
                break;
            case "friendship":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=3&num=";
                break;
            case "memories":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=4&num=";
                break;
            case "good morning":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=5&num=";
                break;
            case "good night":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=6&num=";
                break;
            case "devotional":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=7&num=";
                break;
            case "romantic":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=8&num=";
                break;
            case "sad":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=9&num=";
                break;
            case "wish":
                API_URL = "http://friendvilla.dx.am/shayari.php?cat=10&num=";
                break;
        }
        LIST_ITEMS = new ArrayList<>();
        LIST_MORE_ITEMS = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL, false);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    num = num + 10;
                    readMoreWebpage();
                }
            }
        });
        LoadIntertitial();
        readWebpage();
        adShow();
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                try {
                    Response execute = client.newCall(request).execute();
                    response = Objects.requireNonNull(execute.body()).string();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
        @Override
        protected void onPostExecute(String result) {
            //String[] Data = result.split("<>");
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    ItemClass itemClass = new ItemClass(object.getString("id"),
                            object.getString("cat"), Cat,
                            object.getString("msg"), object.getString("cat"));
                    LIST_ITEMS.add(itemClass);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            movieAdapter = new ItemViewAdapter(LIST_ITEMS, ShayariActivity.this);
            recyclerView.setAdapter(movieAdapter);
        }
    }

    public void readWebpage() {
        ShayariActivity.DownloadWebPageTask task = new ShayariActivity.DownloadWebPageTask();
        task.execute(API_URL + num);

    }

    private class DownloadMoreWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                try {
                    Response execute = client.newCall(request).execute();
                    response = Objects.requireNonNull(execute.body()).string();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
        @Override
        protected void onPostExecute(String result) {
            //String[] Data = result.split("<>");
            try {
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    ItemClass itemClass = new ItemClass(object.getString("id"),
                            object.getString("cat"), Cat,
                            object.getString("msg"), object.getString("cat"));
                    LIST_MORE_ITEMS.add(itemClass);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            movieAdapter.addMoreData(LIST_MORE_ITEMS);
        }
    }

    public void readMoreWebpage() {
        ShayariActivity.DownloadMoreWebPageTask task = new ShayariActivity.DownloadMoreWebPageTask();
        task.execute(API_URL + num);

    }

    private void LoadIntertitial() {
        MobileAds.initialize(ShayariActivity.this, getResources().getString(R.string.AppID));
        interstitialAd = new InterstitialAd(ShayariActivity.this);
        interstitialAd.setAdUnitId(getResources().getString(R.string.Interstitial));
        AdRequest adRequest = new AdRequest.Builder().build();
        interstitialAd.loadAd(adRequest);
    }

    private void showAdsAlert() {
        dialog = new Dialog(this);
        dialog.setContentView(R.layout.ads_dialog);
        final TextView num = (TextView) dialog.findViewById(R.id.time);
        new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long sec = (TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
                num.setText(String.format("%02d", sec));
            }
            @Override
            public void onFinish() {
                num.setText("0");
                if(interstitialAd != null && interstitialAd.isLoaded()){
                    interstitialAd.show();
                }
                dialog.dismiss();
                LoadIntertitial();
                adShow();
            }
        }.start();
        dialog.setCancelable(false);
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
    }

    private void adShow(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(run) {
                    showAdsAlert();
                }
            }
        },50000);
    }

    @Override
    public void onBackPressed() {
        run = false;
        finish();
    }
}
