#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'pokepisode.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import requests
from bs4 import BeautifulSoup
import json
from datetime import datetime
import re
import sys

# This changes almost every week
# Of the many problems in this code, this is the biggest. I must
# scrape this crap
GOGOANIME = "anitaku.to"

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.TitleLabel = QtWidgets.QLabel(self.centralwidget)
        self.TitleLabel.setGeometry(QtCore.QRect(290, 20, 141, 31))
        self.TitleLabel.setObjectName("TitleLabel")
        self.gogoLinkButton = QtWidgets.QPushButton(self.centralwidget)
        self.gogoLinkButton.setGeometry(QtCore.QRect(60, 80, 75, 23))
        self.gogoLinkButton.setObjectName("gogoLinkButton")
        self.gogoLinkButton.clicked.connect(self.display_gogoanime_link)
        self.GoGoStatusLabel = QtWidgets.QLabel(self.centralwidget)
        self.GoGoStatusLabel.setGeometry(QtCore.QRect(60, 120, 500, 23))
        self.GoGoStatusLabel.setObjectName("GoGoStatusLabel")
        self.TorLinkButton = QtWidgets.QPushButton(self.centralwidget)
        self.TorLinkButton.setGeometry(QtCore.QRect(60, 150, 75, 23))
        self.TorLinkButton.setObjectName("TorLinkButton")
        self.TorLinkButton.clicked.connect(self.display_torrent_link)
        self.TorStatusLabel = QtWidgets.QLabel(self.centralwidget)
        self.TorStatusLabel.setGeometry(QtCore.QRect(60, 190, 500, 23))
        self.TorStatusLabel.setObjectName("TorStatusLabel")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        self.menuPokepisode = QtWidgets.QMenu(self.menubar)
        self.menuPokepisode.setObjectName("menuPokepisode")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuPokepisode.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.TitleLabel.setText(_translate("MainWindow", "PokEpisode"))
        self.gogoLinkButton.setText(_translate("MainWindow", "GoGo"))
        self.GoGoStatusLabel.setText(_translate("MainWindow", ""))
        self.TorLinkButton.setText(_translate("MainWindow", "Tor"))
        self.TorStatusLabel.setText(_translate("MainWindow", ""))
        self.menuPokepisode.setTitle(_translate("MainWindow", "Pokepisode"))

    def request(self, url, jsonify=False):
        r = requests.get(url)
        if not r.ok:
            self.show_error(f"Could not request url: {url}")
            return None
        return r.json() if jsonify else r.text

    def show_error(self, message):
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.showMessage(message)
        error_dialog.exec_()

    def gogoanime(self):
        data = self.request("https://ajax.gogocdn.net/ajax/load-list-episode?ep_start=0&ep_end=100000000&id=13784&default_ep=42&alias=pokemon-shinsaku-anime")
        if not data:
            return None
        soup = BeautifulSoup(data, 'html.parser')
        newest = soup.find_all("li")[0]
        number = int(newest.find('div', attrs={'class': 'name'}).text.split(" ")[-1])
        link = f"https://{GOGOANIME}" + newest.find('a')['href'][1:]
        return {"link": link, "number": number}

    def somestuffs(self):
        data = self.request(f"https://some-stuffs.com/")
        if not data:
            return None
        soup = BeautifulSoup(data, 'html.parser')
        newest = soup.find("script", attrs={'id': '__NEXT_DATA__'}).text
        content = json.loads(newest)["props"]["pageProps"]["allPosts"]
        details = [(episode) for episode in content if episode["categories"][0] == "pokemon"][0]
        number = int(details["slug"].split("-")[-1])
        soup = BeautifulSoup(details["mdContent"], 'html.parser')
        url = soup.find("a")['href']
        torrent = url.replace("view", "download") + ".torrent"
        return {"torrent": torrent, "url": url, "number": number}

    def wikipedia():
        data = request("https://en.wikipedia.org/w/index.php?title=Pok%C3%A9mon_Horizons:_The_Series&useskin=vector")
        soup = BeautifulSoup(data, 'html.parser')
        table = soup.find("table", {"class": "wikitable plainrowheaders wikiepisodetable"})
        rows = table.find_all("tr")
        current_date = datetime.now()
        last_episode = {}
        next_episode = {}

        def title_format(title):
            return re.findall('".*?"', title)[0]
        for i, row in enumerate(rows):
            columns = row.find_all("td")
            if len(columns) > 1:
                date_string = columns[6].text.strip().split("(")[-1].replace(")","")
                episode_date = datetime.strptime(date_string, "%Y-%m-%d")
                if episode_date <= current_date:
                    last_episode = {
                        "number": columns[1].text.strip(),
                        "title": title_format(columns[2].text.strip()),
                        "date": date_string
                    }
                else:
                    next_episode = {
                        "number": columns[1].text.strip(),
                        "title": title_format(columns[2].text.strip()),
                        "date": date_string
                    }
                    break
        return (last_episode, next_episode)

    def display_gogoanime_link(self):
        result = self.gogoanime()
        if result:
            self.GoGoStatusLabel.setText(f"GoGoAnime link: {result['link']}")

    def display_torrent_link(self):
        result = self.somestuffs()
        if result:
            self.TorStatusLabel.setText(f"Torrent link: {result['url']}")

    def display_new_episode(self):
        result = self.

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
