package WowneroChanBot;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.util.Random;

public class Memes {

    public static int url = 0;
    public static int authorName = 1;
    public static int authorUrl = 2;
    public static int authorAddress = 3;

    private static final String suchWowWebsiteUrlString = "https://suchwow.xyz";

    public String[] getRandomMeme() {
        int randInt = new Random().nextInt(1, getAmountOfMemes());
        String[] memeData = getMemeData(suchWowWebsiteUrlString + "/post/" + randInt);

        System.out.println(suchWowWebsiteUrlString + "/post/" + randInt);
        return memeData;
    }

    private static String[] getMemeData(String postUrl) {
        String[] memeData = new String[4];

        Document doc = null;
        try {
            doc = Jsoup.connect(postUrl).userAgent("Mozilla/5.0").timeout(10000).get();
            memeData[url] = doc.select("img").get(1).absUrl("src");
            memeData[authorAddress] = doc.select("i").get(2).text();
            memeData[authorName] =  doc.select("a").get(15).text();
            memeData[authorUrl] = suchWowWebsiteUrlString + "/?submitter=" + doc.select("a").get(15).text();

            System.out.println(memeData[url] + "\n" + memeData[authorName] + "\n" + memeData[authorUrl] + "\n" + memeData[authorAddress]);
            return memeData;
        }

        catch (IOException | NullPointerException getRequestFailedException) {
            getRequestFailedException.printStackTrace();
        }
        return null;
    }

    public int getAmountOfMemes() {
        Document document = null;
        try {
            document = Jsoup.connect(suchWowWebsiteUrlString).userAgent("Mozilla/5.0").timeout(10000).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str = document.select("img").attr("alt");

        int lastDigitIndex = 9;

        while (Character.isDigit(str.toCharArray()[lastDigitIndex])) {
            lastDigitIndex++;
        }

        return Integer.parseInt(str.substring(9, lastDigitIndex));
    }

}
