from PyQt5 import QtCore, QtGui, QtWidgets
from FormatMail import Formatter
from SendMail import Ui_ComposeWindow


class Ui_InboxWindow(object):
    def __init__(self, cred):
        self.username, self.password = cred[0], cred[1]

    def setupUi(self, InboxWindow):
        InboxWindow.setObjectName("InboxWindow")
        InboxWindow.resize(660, 637)
        InboxWindow.setMinimumSize(QtCore.QSize(660, 637))
        InboxWindow.setMaximumSize(QtCore.QSize(660, 637))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("./img/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        InboxWindow.setWindowIcon(icon)
        InboxWindow.setStyleSheet("* {\n"
"    background-color: white;\n"
"}")
        self.centralwidget = QtWidgets.QWidget(InboxWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.lbl1Subject = QtWidgets.QLabel(self.centralwidget)
        self.lbl1Subject.setGeometry(QtCore.QRect(10, 10, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.lbl1Subject.setFont(font)
        self.lbl1Subject.setObjectName("lbl1Subject")
        self.lbl1From = QtWidgets.QLabel(self.centralwidget)
        self.lbl1From.setGeometry(QtCore.QRect(10, 50, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8)
        self.lbl1From.setFont(font)
        self.lbl1From.setObjectName("lbl1From")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 110, 641, 20))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.lbl2From = QtWidgets.QLabel(self.centralwidget)
        self.lbl2From.setGeometry(QtCore.QRect(10, 170, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        self.lbl2From.setFont(font)
        self.lbl2From.setObjectName("lbl2From")
        self.lbl2Subject = QtWidgets.QLabel(self.centralwidget)
        self.lbl2Subject.setGeometry(QtCore.QRect(10, 130, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.lbl2Subject.setFont(font)
        self.lbl2Subject.setObjectName("lbl2Subject")
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setGeometry(QtCore.QRect(0, 230, 641, 20))
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.lbl3From = QtWidgets.QLabel(self.centralwidget)
        self.lbl3From.setGeometry(QtCore.QRect(10, 290, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8)
        self.lbl3From.setFont(font)
        self.lbl3From.setObjectName("lbl3From")
        self.lbl4Subject = QtWidgets.QLabel(self.centralwidget)
        self.lbl4Subject.setGeometry(QtCore.QRect(10, 370, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.lbl4Subject.setFont(font)
        self.lbl4Subject.setObjectName("lbl4Subject")
        self.line_3 = QtWidgets.QFrame(self.centralwidget)
        self.line_3.setGeometry(QtCore.QRect(0, 460, 641, 20))
        self.line_3.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_3.setObjectName("line_3")
        self.lbl4From = QtWidgets.QLabel(self.centralwidget)
        self.lbl4From.setGeometry(QtCore.QRect(10, 410, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8)
        self.lbl4From.setFont(font)
        self.lbl4From.setObjectName("lbl4From")
        self.lbl3Subject = QtWidgets.QLabel(self.centralwidget)
        self.lbl3Subject.setGeometry(QtCore.QRect(10, 250, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.lbl3Subject.setFont(font)
        self.lbl3Subject.setObjectName("lbl3Subject")
        self.line_4 = QtWidgets.QFrame(self.centralwidget)
        self.line_4.setGeometry(QtCore.QRect(0, 350, 641, 20))
        self.line_4.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_4.setObjectName("line_4")
        self.lbl5Subject = QtWidgets.QLabel(self.centralwidget)
        self.lbl5Subject.setGeometry(QtCore.QRect(10, 480, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.lbl5Subject.setFont(font)
        self.lbl5Subject.setObjectName("lbl5Subject")
        self.lbl5From = QtWidgets.QLabel(self.centralwidget)
        self.lbl5From.setGeometry(QtCore.QRect(10, 520, 221, 21))
        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8)
        self.lbl5From.setFont(font)
        self.lbl5From.setObjectName("lbl5From")
        self.composeMail = QtWidgets.QPushButton(self.centralwidget)
        self.composeMail.setGeometry(QtCore.QRect(580, 550, 51, 51))
        self.composeMail.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("img/compose.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.composeMail.setIcon(icon1)
        self.composeMail.setIconSize(QtCore.QSize(150, 150))
        self.composeMail.setDefault(True)
        self.composeMail.setFlat(True)
        self.composeMail.setObjectName("composeMail")
        self.composeMail.clicked.connect(self.sendMail)

        self.backToLogin = QtWidgets.QPushButton(self.centralwidget)
        self.backToLogin.setGeometry(QtCore.QRect(30, 570, 90, 28))
        self.backToLogin.clicked.connect(self.Login)

        font = QtGui.QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(13)
        font.setItalic(False)
        self.backToLogin.setFont(font)
        self.backToLogin.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.backToLogin.setStyleSheet("color: rgb(26, 115, 232);")
        self.backToLogin.setFlat(True)
        self.backToLogin.setObjectName("backToLogin")
        self.lbl1Time = QtWidgets.QLabel(self.centralwidget)
        self.lbl1Time.setGeometry(QtCore.QRect(250, 80, 111, 20))
        font = QtGui.QFont()
        font.setFamily("Ubuntu Light")
        self.lbl1Time.setFont(font)
        self.lbl1Time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl1Time.setObjectName("lbl1Time")
        self.lbl2Time = QtWidgets.QLabel(self.centralwidget)
        self.lbl2Time.setGeometry(QtCore.QRect(250, 200, 111, 20))
        font = QtGui.QFont()
        font.setFamily("Ubuntu Light")
        self.lbl2Time.setFont(font)
        self.lbl2Time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl2Time.setObjectName("lbl2Time")
        self.lbl3Time = QtWidgets.QLabel(self.centralwidget)
        self.lbl3Time.setGeometry(QtCore.QRect(250, 320, 111, 20))
        font = QtGui.QFont()
        font.setFamily("Ubuntu Light")
        self.lbl3Time.setFont(font)
        self.lbl3Time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl3Time.setObjectName("lbl3Time")
        self.lbl4Time = QtWidgets.QLabel(self.centralwidget)
        self.lbl4Time.setGeometry(QtCore.QRect(250, 440, 111, 20))
        font = QtGui.QFont()
        font.setFamily("Ubuntu Light")
        self.lbl4Time.setFont(font)
        self.lbl4Time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl4Time.setObjectName("lbl4Time")
        self.lbl5Time = QtWidgets.QLabel(self.centralwidget)
        self.lbl5Time.setGeometry(QtCore.QRect(250, 550, 111, 20))
        font = QtGui.QFont()
        font.setFamily("Ubuntu Light")
        self.lbl5Time.setFont(font)
        self.lbl5Time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl5Time.setObjectName("lbl5Time")
        self.txt1Body = QtWidgets.QTextBrowser(self.centralwidget)
        self.txt1Body.setGeometry(QtCore.QRect(250, 10, 391, 61))
        self.txt1Body.setObjectName("txt1Body")
        self.txt2Body = QtWidgets.QTextBrowser(self.centralwidget)
        self.txt2Body.setGeometry(QtCore.QRect(250, 130, 391, 61))
        self.txt2Body.setObjectName("txt2Body")
        self.txt3Body = QtWidgets.QTextBrowser(self.centralwidget)
        self.txt3Body.setGeometry(QtCore.QRect(250, 250, 391, 61))
        self.txt3Body.setObjectName("txt3Body")
        self.txt4Body = QtWidgets.QTextBrowser(self.centralwidget)
        self.txt4Body.setGeometry(QtCore.QRect(250, 370, 391, 61))
        self.txt4Body.setObjectName("txt4Body")
        self.txt5Body = QtWidgets.QTextBrowser(self.centralwidget)
        self.txt5Body.setGeometry(QtCore.QRect(250, 480, 391, 61))
        self.txt5Body.setObjectName("txt5Body")
        InboxWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(InboxWindow)
        self.statusbar.setObjectName("statusbar")
        InboxWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, InboxWindow):
        _translate = QtCore.QCoreApplication.translate
        InboxWindow.setWindowTitle(_translate("InboxWindow", "Ирсэн мэйл"))
        self.lbl1Subject.setText(_translate("InboxWindow", "Subject"))
        self.lbl1From.setText(_translate("InboxWindow", "From"))
        self.lbl2From.setText(_translate("InboxWindow", "From"))
        self.lbl2Subject.setText(_translate("InboxWindow", "Subject"))
        self.lbl3From.setText(_translate("InboxWindow", "From"))
        self.lbl4Subject.setText(_translate("InboxWindow", "Subject"))
        self.lbl4From.setText(_translate("InboxWindow", "From"))
        self.lbl3Subject.setText(_translate("InboxWindow", "Subject"))
        self.lbl5Subject.setText(_translate("InboxWindow", "Subject"))
        self.lbl5From.setText(_translate("InboxWindow", "From"))
        self.backToLogin.setToolTip(_translate("InboxWindow", "Үүнийг дарж шинэ хаяг нээнэ үү"))
        self.backToLogin.setText(_translate("InboxWindow", "Буцах"))
        self.lbl1Time.setText(_translate("InboxWindow", "Time"))
        self.lbl2Time.setText(_translate("InboxWindow", "Time"))
        self.lbl3Time.setText(_translate("InboxWindow", "Time"))
        self.lbl4Time.setText(_translate("InboxWindow", "Time"))
        self.lbl5Time.setText(_translate("InboxWindow", "Time"))
        self.inbox()
    def sendMail(self):
        print('[+] Trying to open new window')
        from SendMail import Ui_ComposeWindow
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_ComposeWindow([self.username, self.password])
        self.ui.setupUi(self.window)
        self.window.show()

    def Login(self):
        print('[-] It will not work')
        from Login import Ui_LoginWindow
        self.window = QtWidgets.QMainWindow()
        self.ui = Ui_LoginWindow()
        self.ui.setupUi(self.window)
        self.window.show()

    def inbox(self):
        import smtplib
        import time
        import imaplib
        import email
        from base64 import b64decode
        try:
            FROM_EMAIL  = self.username
            FROM_PWD    = self.password
            SMTP_SERVER = "imap.gmail.com"
            SMTP_PORT   = 993
            mail = imaplib.IMAP4_SSL(SMTP_SERVER)
            mail.login(FROM_EMAIL,FROM_PWD)
            mail.select('inbox')

            type, data = mail.search(None, 'ALL')
            mail_ids = data[0]

            id_list = mail_ids.split()
            first_email_id = int(id_list[0])
            latest_email_id = int(id_list[-1])
            flags = []
            for i in range(latest_email_id, first_email_id, -1):
                done = False
                typ, data = mail.fetch(str(i), '(RFC822)')
                for response_part in data:
                    if isinstance(response_part, tuple):
                        msg, body = email.message_from_string(response_part[1].decode()), ''
                        for part in msg.walk():
                            if part.get_content_type() == 'text/plain':
                                try: body += part.get_payload()
                                except: pass
                        try: body = b64decode(body).decode()
                        except: body = body
                        print(f'[+] Getting gmail: {len(flags) + 1}')
                        flags.append((msg, body))
                        if len(flags) >= 5:
                            done = True
                            break
                    if done: break
                if done: break
        except: pass
        # Mail - 1
        self.lbl1Subject.setText(Formatter.cleanSubject(flags[0][0]['subject']))
        self.lbl1From.setText(Formatter.cleanFrom(flags[0][0]['from']))
        self.lbl1Time.setText(Formatter.cleanTime(flags[0][0]['Date']))
        self.txt1Body.setText(Formatter.cleanBody(flags[0][1]))
        # Mail - 2
        self.lbl2Subject.setText(Formatter.cleanSubject(flags[1][0]['subject']))
        self.lbl2From.setText(Formatter.cleanFrom(flags[1][0]['from']))
        self.lbl2Time.setText(Formatter.cleanTime(flags[1][0]['Date']))
        self.txt2Body.setText(Formatter.cleanBody(flags[1][1]))
        # Mail - 3
        self.lbl3Subject.setText(Formatter.cleanSubject(flags[2][0]['subject']))
        self.lbl3Time.setText(Formatter.cleanTime(flags[2][0]['Date']))
        self.lbl3From.setText(Formatter.cleanFrom(flags[2][0]['from']))
        self.txt3Body.setText(Formatter.cleanBody(flags[2][1]))
        # Mail - 4
        self.lbl4Subject.setText(Formatter.cleanSubject(flags[3][0]['subject']))
        self.lbl4Time.setText(Formatter.cleanTime(flags[3][0]['Date']))
        self.lbl4From.setText(Formatter.cleanFrom(flags[3][0]['from']))
        self.txt4Body.setText(Formatter.cleanBody(flags[3][1]))
        # Mail - 5
        self.lbl5Subject.setText(Formatter.cleanSubject(flags[4][0]['subject']))
        self.lbl5From.setText(Formatter.cleanFrom(flags[4][0]['from']))
        self.lbl5Time.setText(Formatter.cleanTime(flags[4][0]['Date']))
        self.txt5Body.setText(Formatter.cleanBody(flags[4][1]))


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