<gh_stars>10-100
from PyQt5.QtWidgets import QMessageBox, QTreeWidgetItem
from PyQt5.QtGui import QColor, QBrush, QPalette, QFont
from PyQt5.QtCore import QObject, Qt, pyqtSignal

import asyncio
import re

from base.https.tassomai import Tassomai
from base.common import gather_answers

class Lookup:

    def __init__(self, base):
        self.ui = base
        self.tree = self.ui.ui.tree
        self.database = self.ui.database.all()

    def check_begin(self):
        if self.ui.ui.question:
            asyncio.run(self.search())
        else:
            asyncio.run(self.check())

    async def check(self):
        if self.ui.ui.quiz_url.text().__contains__('courseId=') and self.ui.ui.quiz_url.text().__contains__('playlistId='):
            try:
                tassomai = Tassomai({})
                discipline = int(re.search('\d', self.ui.ui.quiz_url.text())[0])
                tassomai.set_discipline(discipline)
                email = self.ui.ui.emailTassomai.text()
                password = self.ui.ui.password<PASSWORD>.text()
                login = await tassomai.login(email, password)
                if login == 'error':
                    msg = QMessageBox()
                    msg.setWindowTitle("An error occured")
                    msg.setText("Failed to login to Tassomai.")
                    msg.setInformativeText("Invalid credentials maybe?")
                    msg.setIcon(QMessageBox.Warning)
                    msg.setStandardButtons(QMessageBox.Ok)
                    msg.setDefaultButton(QMessageBox.Ok)
                    msg.exec_()

                    return

                courseId = int(re.search('courseId=\d+', self.ui.ui.quiz_url.text())[0].strip('courseId='))
                playlistId = int(re.search('playlistId=\d+', self.ui.ui.quiz_url.text())[0].strip('playlistId='))
                data = await tassomai.special_extract(courseId, playlistId)

                for q in data['questions']: # removing double spaces
                    q['text'] = q['text'].replace("  ", " ")
                    for ie, ans in enumerate(q['answers']):
                        q['answers'][ie]['text'] = ans['text'].replace("  ", " ")
                data['questions'] = list(sorted(data['questions'], key=lambda k: k['text'])) # sorting the questions in alphabetical order
                await self.lookup(data)
            except:
                msg = QMessageBox()
                msg.setWindowTitle("An error occured")
                msg.setText("An unknown error occured.")
                msg.setIcon(QMessageBox.Warning)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.setDefaultButton(QMessageBox.Ok)
                msg.exec_()
        else:
            print("e")
            msg = QMessageBox()
            msg.moveToThread(self.ui.lookup_thread)
            msg.setWindowTitle("An error occured")
            msg.setText("Invalid quiz URL.")
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.exec_()

    async def search(self):
        self.ui.ui.tree.clear()
        question = self.ui.ui.quiz_url.text().strip()
        if question == "":
            msg = QMessageBox()
            msg.setWindowTitle("An error occured")
            msg.setText("Input required.")
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.exec_()
            return
        data = list(filter(lambda k: k.lower().startswith(question.lower()), self.database))

        for question in data:
            item = QTreeWidgetItem([question])
            self.tree.addTopLevelItem(item)

            red_brush = QBrush(QColor(155, 0, 0))
            green_brush = QBrush(QColor(0, 155, 0))
            blue_brush = QBrush(QColor(30, 59, 166))

            brush = green_brush
            answers = list(self.database[question].keys())

            for answer_set in answers:
                answers_list = eval(answer_set)
                a = self.database[question][answer_set]
                current_answers = list(a.keys()) if type(a) == dict else [a]
                for answer in answers_list:
                    child = QTreeWidgetItem(['• ' + answer])
                    if answer in current_answers:
                        brush = green_brush
                    else:
                        brush = red_brush
                    child.setForeground(0, brush)
                    item.addChild(child)
                if answers.index(answer_set)+1 < len(answers):
                    brush = blue_brush
                    child = QTreeWidgetItem(['-------- OTHER SET OF ANSWERS TO QUESTION --------'])
                    child.setForeground(0, brush)
                    item.addChild(child)

    async def lookup(self, data):
        top = QTreeWidgetItem([data['title']])
        font = QFont()
        font.setBold(True)
        top.setFont(0, font)
        self.tree.addTopLevelItem(top)
        for index, question in enumerate(data['questions'], start=1):
            item = QTreeWidgetItem([f'{index}. ' + question['text']])
            top.addChild(item)

            red_brush = QBrush(QColor(155, 0, 0))
            green_brush = QBrush(QColor(0, 155, 0))

            brush = green_brush
            answers = []
            current_answers = str(gather_answers(question['answers']))
            if question['text'] in self.database:
                if current_answers in self.database[question['text']]:
                    db = self.database[question['text']][current_answers]
                    answers = list(db.keys()) if type(db) == dict else [db]

            for answer in question['answers']:
                child = QTreeWidgetItem(['• ' + answer['text']])
                if len(answers) == 0:
                    brush = green_brush
                elif answer['text'] in answers:
                    brush = green_brush
                else:
                    brush = red_brush
                child.setForeground(0, brush)
                item.addChild(child)

class ExtraLookup(QObject, Lookup):

    showSubject = pyqtSignal(list)

    def __init__(self, base, parent=None):
        super().__init__(base=base, parent=parent)

    def extra_begin(self):
        asyncio.run(self.extra())

    async def extra(self):
        tassomai = Tassomai({})
        email = self.ui.ui.emailTassomai.text()
        password = self.ui.ui.passwordTassomai.text()
        login = await tassomai.login(email, password)
        if login == 'error':
            self.ui.ui.extra_lookup.setDisabled(True)
            text = self.ui.ui.info_label.text()
            self.ui.ui.info_label.setText("INVALID CREDENTIALS")
            palette = QPalette()
            brush = QBrush(QColor(181, 21, 21))
            brush.setStyle(Qt.SolidPattern)
            palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
            palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
            self.ui.ui.info_label.setPalette(palette)
            self.thread().sleep(2)
            palette = QPalette()
            brush = QBrush(QColor(30, 59, 166))
            brush.setStyle(Qt.SolidPattern)
            palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
            palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
            self.ui.ui.info_label.setPalette(palette)
            self.ui.ui.info_label.setText(text)
            self.ui.ui.extra_lookup.setDisabled(False)

            return

        disciplines = await tassomai.extract_disciplines()
        tassomai.set_discipline(disciplines[0]['id'])  # just in case for some reason the only subject's discipline ID isn't equal to 1

        if len(disciplines) > 1:
            self.showSubject.emit(disciplines)
            await asyncio.sleep(1.00)
            while not self.ui.subject.done:  # Waiting for user to choose subject and adding time wait between each loop to avoid crash
                await asyncio.sleep(0.10)
            tassomai.set_discipline(self.ui.subject.discipline)

        quizzes = await tassomai.extract_extra_data()
        for quiz in quizzes['quizzes']:
            data = await tassomai.special_extract(quiz['courseId'], quiz['playlistId'])

            for q in data['questions']:
                q['text'] = q['text'].replace("  ", " ")
                for ie, ans in enumerate(q['answers']):
                    q['answers'][ie]['text'] = ans['text'].replace("  ", " ")
            data['questions'] = list(sorted(data['questions'], key=lambda k: k['text']))
            await self.lookup(data)
from PyQt5.QtWidgets import QMessageBox, QTreeWidgetItem
from PyQt5.QtGui import QColor, QBrush, QPalette, QFont
from PyQt5.QtCore import QObject, Qt, pyqtSignal

import asyncio
import re

from base.https.tassomai import Tassomai
from base.common import gather_answers

class Lookup:

    def __init__(self, base):
        self.ui = base
        self.tree = self.ui.ui.tree
        self.database = self.ui.database.all()

    def check_begin(self):
        if self.ui.ui.question:
            asyncio.run(self.search())
        else:
            asyncio.run(self.check())

    async def check(self):
        if self.ui.ui.quiz_url.text().__contains__('courseId=') and self.ui.ui.quiz_url.text().__contains__('playlistId='):
            try:
                tassomai = Tassomai({})
                discipline = int(re.search('\d', self.ui.ui.quiz_url.text())[0])
                tassomai.set_discipline(discipline)
                email = self.ui.ui.emailTassomai.text()
                password = self.ui.ui.password<PASSWORD>.text()
                login = await tassomai.login(email, password)
                if login == 'error':
                    msg = QMessageBox()
                    msg.setWindowTitle("An error occured")
                    msg.setText("Failed to login to Tassomai.")
                    msg.setInformativeText("Invalid credentials maybe?")
                    msg.setIcon(QMessageBox.Warning)
                    msg.setStandardButtons(QMessageBox.Ok)
                    msg.setDefaultButton(QMessageBox.Ok)
                    msg.exec_()

                    return

                courseId = int(re.search('courseId=\d+', self.ui.ui.quiz_url.text())[0].strip('courseId='))
                playlistId = int(re.search('playlistId=\d+', self.ui.ui.quiz_url.text())[0].strip('playlistId='))
                data = await tassomai.special_extract(courseId, playlistId)

                for q in data['questions']: # removing double spaces
                    q['text'] = q['text'].replace("  ", " ")
                    for ie, ans in enumerate(q['answers']):
                        q['answers'][ie]['text'] = ans['text'].replace("  ", " ")
                data['questions'] = list(sorted(data['questions'], key=lambda k: k['text'])) # sorting the questions in alphabetical order
                await self.lookup(data)
            except:
                msg = QMessageBox()
                msg.setWindowTitle("An error occured")
                msg.setText("An unknown error occured.")
                msg.setIcon(QMessageBox.Warning)
                msg.setStandardButtons(QMessageBox.Ok)
                msg.setDefaultButton(QMessageBox.Ok)
                msg.exec_()
        else:
            print("e")
            msg = QMessageBox()
            msg.moveToThread(self.ui.lookup_thread)
            msg.setWindowTitle("An error occured")
            msg.setText("Invalid quiz URL.")
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.exec_()

    async def search(self):
        self.ui.ui.tree.clear()
        question = self.ui.ui.quiz_url.text().strip()
        if question == "":
            msg = QMessageBox()
            msg.setWindowTitle("An error occured")
            msg.setText("Input required.")
            msg.setIcon(QMessageBox.Warning)
            msg.setStandardButtons(QMessageBox.Ok)
            msg.setDefaultButton(QMessageBox.Ok)
            msg.exec_()
            return
        data = list(filter(lambda k: k.lower().startswith(question.lower()), self.database))

        for question in data:
            item = QTreeWidgetItem([question])
            self.tree.addTopLevelItem(item)

            red_brush = QBrush(QColor(155, 0, 0))
            green_brush = QBrush(QColor(0, 155, 0))
            blue_brush = QBrush(QColor(30, 59, 166))

            brush = green_brush
            answers = list(self.database[question].keys())

            for answer_set in answers:
                answers_list = eval(answer_set)
                a = self.database[question][answer_set]
                current_answers = list(a.keys()) if type(a) == dict else [a]
                for answer in answers_list:
                    child = QTreeWidgetItem(['• ' + answer])
                    if answer in current_answers:
                        brush = green_brush
                    else:
                        brush = red_brush
                    child.setForeground(0, brush)
                    item.addChild(child)
                if answers.index(answer_set)+1 < len(answers):
                    brush = blue_brush
                    child = QTreeWidgetItem(['-------- OTHER SET OF ANSWERS TO QUESTION --------'])
                    child.setForeground(0, brush)
                    item.addChild(child)

    async def lookup(self, data):
        top = QTreeWidgetItem([data['title']])
        font = QFont()
        font.setBold(True)
        top.setFont(0, font)
        self.tree.addTopLevelItem(top)
        for index, question in enumerate(data['questions'], start=1):
            item = QTreeWidgetItem([f'{index}. ' + question['text']])
            top.addChild(item)

            red_brush = QBrush(QColor(155, 0, 0))
            green_brush = QBrush(QColor(0, 155, 0))

            brush = green_brush
            answers = []
            current_answers = str(gather_answers(question['answers']))
            if question['text'] in self.database:
                if current_answers in self.database[question['text']]:
                    db = self.database[question['text']][current_answers]
                    answers = list(db.keys()) if type(db) == dict else [db]

            for answer in question['answers']:
                child = QTreeWidgetItem(['• ' + answer['text']])
                if len(answers) == 0:
                    brush = green_brush
                elif answer['text'] in answers:
                    brush = green_brush
                else:
                    brush = red_brush
                child.setForeground(0, brush)
                item.addChild(child)

class ExtraLookup(QObject, Lookup):

    showSubject = pyqtSignal(list)

    def __init__(self, base, parent=None):
        super().__init__(base=base, parent=parent)

    def extra_begin(self):
        asyncio.run(self.extra())

    async def extra(self):
        tassomai = Tassomai({})
        email = self.ui.ui.emailTassomai.text()
        password = self.ui.ui.passwordTassomai.text()
        login = await tassomai.login(email, password)
        if login == 'error':
            self.ui.ui.extra_lookup.setDisabled(True)
            text = self.ui.ui.info_label.text()
            self.ui.ui.info_label.setText("INVALID CREDENTIALS")
            palette = QPalette()
            brush = QBrush(QColor(181, 21, 21))
            brush.setStyle(Qt.SolidPattern)
            palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
            palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
            self.ui.ui.info_label.setPalette(palette)
            self.thread().sleep(2)
            palette = QPalette()
            brush = QBrush(QColor(30, 59, 166))
            brush.setStyle(Qt.SolidPattern)
            palette.setBrush(QPalette.Active, QPalette.WindowText, brush)
            palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)
            self.ui.ui.info_label.setPalette(palette)
            self.ui.ui.info_label.setText(text)
            self.ui.ui.extra_lookup.setDisabled(False)

            return

        disciplines = await tassomai.extract_disciplines()
        tassomai.set_discipline(disciplines[0]['id'])  # just in case for some reason the only subject's discipline ID isn't equal to 1

        if len(disciplines) > 1:
            self.showSubject.emit(disciplines)
            await asyncio.sleep(1.00)
            while not self.ui.subject.done:  # Waiting for user to choose subject and adding time wait between each loop to avoid crash
                await asyncio.sleep(0.10)
            tassomai.set_discipline(self.ui.subject.discipline)

        quizzes = await tassomai.extract_extra_data()
        for quiz in quizzes['quizzes']:
            data = await tassomai.special_extract(quiz['courseId'], quiz['playlistId'])

            for q in data['questions']:
                q['text'] = q['text'].replace("  ", " ")
                for ie, ans in enumerate(q['answers']):
                    q['answers'][ie]['text'] = ans['text'].replace("  ", " ")
            data['questions'] = list(sorted(data['questions'], key=lambda k: k['text']))
            await self.lookup(data)
# removing double spaces # sorting the questions in alphabetical order # just in case for some reason the only subject's discipline ID isn't equal to 1 # Waiting for user to choose subject and adding time wait between each loop to avoid crash