import os.path
import json
import urllib.request
import webbrowser
import random

from ..Qt import QtGui, QtCore, QtWidgets
from .._py.pokemon import Ui_Dialog

random.seed()


class QPokemon(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, number=None, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        self._js = json.load(open(os.path.join(path_to_module, 'utils', 'pokemon.json'), 'r'), encoding='UTF-8')
        self._id = 0

        if number is not None and number in range(1, len(self._js)+1):
            poke_nr = f'{number:03d}'
            self._id = number
        else:
            poke_nr = f'{random.randint(1, len(self._js)):03d}'
            self._id = int(poke_nr)

        self._pokemon = None
        self.show_pokemon(poke_nr)
        self.label_15.linkActivated.connect(lambda x: webbrowser.open(x))

        self.buttonBox.clicked.connect(self.randomize)
        self.next_button.clicked.connect(self.show_next)
        self.prev_button.clicked.connect(self.show_prev)

    def show_pokemon(self, nr):
        self._pokemon = self._js[nr]
        self.setWindowTitle('Pokémon: ' + self._pokemon['Deutsch'])

        for i in range(self.tabWidget.count(), -1, -1):
            print('i', self.tabWidget.count(), i)
            try:
                self.tabWidget.widget(i).deleteLater()
            except AttributeError:
                pass

        for n, img in self._pokemon['Bilder']:
            w = QtWidgets.QWidget()
            vl = QtWidgets.QVBoxLayout()
            l = QtWidgets.QLabel(self)
            l.setAlignment(QtCore.Qt.AlignHCenter)
            pixmap = QtGui.QPixmap()

            try:
                pixmap.loadFromData(urllib.request.urlopen(img, timeout=0.5).read())
            except IOError:
                l.setText(n)
            else:
                sc_pixmap = pixmap.scaled(256, 256, QtCore.Qt.KeepAspectRatio)
                l.setPixmap(sc_pixmap)

            vl.addWidget(l)
            w.setLayout(vl)
            self.tabWidget.addTab(w, n)

        if len(self._pokemon['Bilder']) <= 1:
            self.tabWidget.tabBar().setVisible(False)
        else:
            self.tabWidget.tabBar().setVisible(True)
        self.tabWidget.adjustSize()

        self.name.clear()
        keys = ['National-Dex', 'Kategorie', 'Typ', 'Größe', 'Gewicht', 'Farbe', 'Link']
        label_list = [self.pokedex_nr, self.category, self.poketype, self.weight, self.height, self.color, self.info]
        for (k, label) in zip(keys, label_list):
            v = self._pokemon[k]
            if isinstance(v, list):
                v = os.path.join('', *v)

            if k == 'Link':
                v = '<a href={}>{}</a>'.format(v, v)

            label.setText(v)

        for k in ['Deutsch', 'Japanisch', 'Englisch', 'Französisch']:
            v = self._pokemon[k]
            self.name.addItem(k + ': ' + v)

        self.adjustSize()

    def randomize(self, idd):
        if idd.text() == 'Retry':
            new_number = f'{random.randint(1, len(self._js)):03d}'
            self._id = int(new_number)
            self.show_pokemon(new_number)
        else:
            self.close()

    def show_next(self):
        new_number = self._id + 1
        if new_number > len(self._js):
            new_number = 1
        self._id = new_number
        self.show_pokemon(f'{new_number:03d}')

    def show_prev(self):
        new_number = self._id - 1
        if new_number == 0:
            new_number = len(self._js)
        self._id = new_number
        self.show_pokemon(f'{new_number:03d}')
