# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'signup.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# 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.

import time
import datetime
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QDialog, QApplication
from database import DB_Users
from qmessagebox import Ui_Qmessagebox
from random import randrange
import smtplib
from verify import Ui_Verify
import senderdetail


class Ui_SignUp(QtWidgets.QMainWindow): ## Changed argument object to this and browse start working
    """
    GUI for Create New Account
    """
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 800)
        MainWindow.setStyleSheet("background-color: rgb(173, 239, 209);")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(50, 50, 700, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox.setFont(font)
        self.groupBox.setStyleSheet("")
        self.groupBox.setObjectName("groupBox")
        self.firstName = QtWidgets.QLineEdit(self.groupBox)
        self.firstName.setGeometry(QtCore.QRect(25, 50, 200, 35))
        self.firstName.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.firstName.setObjectName("firstName")
        self.middleName = QtWidgets.QLineEdit(self.groupBox)
        self.middleName.setGeometry(QtCore.QRect(250, 50, 200, 35))
        self.middleName.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.middleName.setObjectName("middleName")
        self.lastName = QtWidgets.QLineEdit(self.groupBox)
        self.lastName.setGeometry(QtCore.QRect(475, 50, 200, 35))
        self.lastName.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.lastName.setObjectName("lastName")
        self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QtCore.QRect(50, 200, 700, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox_2.setFont(font)
        self.groupBox_2.setObjectName("groupBox_2")
        self.emailId = QtWidgets.QLineEdit(self.groupBox_2)
        self.emailId.setGeometry(QtCore.QRect(25, 50, 550, 35))
        self.emailId.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.emailId.setObjectName("emailId")
        self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_3.setGeometry(QtCore.QRect(50, 350, 200, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox_3.setFont(font)
        self.groupBox_3.setObjectName("groupBox_3")
        self.dateOfBirth = QtWidgets.QDateEdit(self.groupBox_3)
        self.dateOfBirth.setGeometry(QtCore.QRect(35, 50, 130, 35))
        self.dateOfBirth.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.dateOfBirth.setObjectName("dateOfBirth")
        self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_4.setGeometry(QtCore.QRect(300, 350, 451, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox_4.setFont(font)
        self.groupBox_4.setObjectName("groupBox_4")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.groupBox_4)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(30, 30, 391, 61))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.imageFile = QtWidgets.QLineEdit(self.horizontalLayoutWidget)
        self.imageFile.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.imageFile.setObjectName("imageFile")
        self.horizontalLayout_5.addWidget(self.imageFile)
        self.browseImage = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.browseImage.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.browseImage.setObjectName("browseImage")
        self.horizontalLayout_5.addWidget(self.browseImage)
        self.groupBox_5 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_5.setGeometry(QtCore.QRect(50, 500, 341, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox_5.setFont(font)
        self.groupBox_5.setObjectName("groupBox_5")
        self.password = QtWidgets.QLineEdit(self.groupBox_5)
        self.password.setGeometry(QtCore.QRect(25, 50, 270, 35))
        self.password.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.password.setObjectName("password")
        self.groupBox_6 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_6.setGeometry(QtCore.QRect(420, 500, 331, 100))
        font = QtGui.QFont()
        font.setFamily("FrankRuehl")
        font.setPointSize(18)
        self.groupBox_6.setFont(font)
        self.groupBox_6.setObjectName("groupBox_6")
        self.confPassword = QtWidgets.QLineEdit(self.groupBox_6)
        self.confPassword.setGeometry(QtCore.QRect(25, 50, 270, 35))
        self.confPassword.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
        self.confPassword.setEchoMode(QtWidgets.QLineEdit.Password)
        self.confPassword.setObjectName("confPassword")
        self.horizontalLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(399, 660, 351, 41))
        self.horizontalLayoutWidget_2.setObjectName("horizontalLayoutWidget_2")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.signUp = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.signUp.setFont(font)
        self.signUp.setStyleSheet("")
        self.signUp.setObjectName("signUp")
        self.horizontalLayout_6.addWidget(self.signUp)
        self.reset = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.reset.setFont(font)
        self.reset.setObjectName("reset")
        self.horizontalLayout_6.addWidget(self.reset)
        self.logIn = QtWidgets.QPushButton(self.horizontalLayoutWidget_2)
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.logIn.setFont(font)
        self.logIn.setObjectName("logIn")
        self.horizontalLayout_6.addWidget(self.logIn)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.reset.clicked.connect(self.confPassword.clear)
        self.reset.clicked.connect(self.imageFile.clear)
        self.reset.clicked.connect(self.password.clear)
        self.reset.clicked.connect(self.dateOfBirth.clear)
        self.reset.clicked.connect(self.emailId.clear)
        self.reset.clicked.connect(self.firstName.clear)
        self.reset.clicked.connect(self.middleName.clear)
        self.reset.clicked.connect(self.lastName.clear)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        self.signUp.clicked.connect(lambda: self.signup(MainWindow))
        self.browseImage.clicked.connect(self.browsefiles)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Sign Up"))
        self.groupBox.setTitle(_translate("MainWindow", "Name"))
        self.firstName.setPlaceholderText(_translate("MainWindow", "First Name"))
        self.middleName.setPlaceholderText(_translate("MainWindow", "Middle Name"))
        self.lastName.setPlaceholderText(_translate("MainWindow", "Last Name"))
        self.groupBox_2.setTitle(_translate("MainWindow", "Email"))
        self.emailId.setPlaceholderText(_translate("MainWindow", "Email"))
        self.groupBox_3.setTitle(_translate("MainWindow", "Date of Birth"))
        self.groupBox_4.setTitle(_translate("MainWindow", "Image"))
        self.imageFile.setPlaceholderText(_translate("MainWindow", "Image"))
        self.browseImage.setText(_translate("MainWindow", "Browse"))
        self.groupBox_5.setTitle(_translate("MainWindow", "Password"))
        self.password.setPlaceholderText(_translate("MainWindow", "Password"))
        self.groupBox_6.setTitle(_translate("MainWindow", "Conform Password"))
        self.confPassword.setPlaceholderText(_translate("MainWindow", "Re-enter Password"))
        self.signUp.setText(_translate("MainWindow", "SIGNUP"))
        self.reset.setText(_translate("MainWindow", "RESET"))
        self.logIn.setText(_translate("MainWindow", "LOGIN"))

    def signup(self, MainWindow):
        if self.firstName.text() and self.lastName.text():
            if self.dateOfBirth.text():
                if self.imageFile.text():
                    if '@gmail.com' in self.emailId.text():
                        if self.password.text() and self.password.text() == self.confPassword.text():
                            email = self.emailId.text()
                            password = self.password.text()
                            datetime = self.get_time_str()
                            firstname = self.firstName.text()
                            if self.middleName.text():
                                middlename = self.middleName.text()
                            else:
                                middlename = None
                            lastname = self.lastName.text()
                            dateofbirth = self.dateOfBirth.text()
                            imagefile = self.imageFile.text()

                            self.otp(email,
                                     password,
                                     datetime,
                                     firstname,
                                     lastname,
                                     dateofbirth,
                                     imagefile,
                                     middlename,
                                     MainWindow)
                        else:
                            self.popup("Password", "Password is not same !!")
                    else:
                        self.popup("Email", "Please Enter Valid Email Id !!")
                else:
                    self.popup("Image", "Please select Image !!")
            else:
                self.popup("Date Of Birth", "Please Enter Date of Birth !!")
        else:
            self.popup("Name", "Please Enter your Name !!")

    def select_random(self):
        rand_all = ''
        for i in range(6):
            rand_one = randrange(10)
            rand_all += str(rand_one)
        return rand_all

    def otp(self,
            email,
            password,
            datetime,
            firstname,
            lastname,
            dateofbirth,
            imagefile,
            middlename,
            MainWindow):
        try:
            obj = smtplib.SMTP("smtp.gmail.com", 587)
            obj.starttls()
            obj.login(senderdetail.EMAIL, senderdetail.PASSWORD)
            subject = "Verify OTP"
            sent_otp = self.select_random()
            body = f"OTP for E-MARS is \n{sent_otp}"
            message = f"Subject:{subject}\n\n{body}"
            obj.sendmail(senderdetail.EMAIL, [email], message)
            obj.quit()
            self.openverify(sent_otp,
                            email,
                            password,
                            datetime,
                            firstname,
                            lastname,
                            dateofbirth,
                            imagefile,
                            middlename,
                            MainWindow)
        except:
            self.popup("Network", "May be your device is not connected to Network. Please Check your Network connection.")

    def openverify(self,
                   sent_otp,
                   email,
                   password,
                   datetime,
                   firstname,
                   lastname,
                   dateofbirth,
                   imagefile,
                   middlename,
                   MainWindow):
        self.window = QtWidgets.QMainWindow()
        self.window.setFixedSize(500, 400)
        self.ui = Ui_Verify(sent_otp,
                            email,
                            password,
                            datetime,
                            firstname,
                            lastname,
                            dateofbirth,
                            imagefile,
                            middlename,
                            signupwindow=MainWindow)
        self.ui.setupUi(self.window)
        self.window.show()


    def get_time_str(self):
        """
        This function for Real time

        Returns:
            str_time (str): return current time
        """
        timestamp = int(time.time())
        value = datetime.datetime.fromtimestamp(timestamp)
        str_time = value.strftime('%Y-%m-%d %H:%M:%S')

        return str_time

    def popup(self, title, text):
        Ui_Qmessagebox().qmessagebox(title, text)

    def browsefiles(self):
        filename = QFileDialog.getOpenFileName(self, 'Open file', r'D:\pyqt5\img', 'Images (*.png, *.xmp *.jpg)')
        self.imageFile.setText(filename[0])



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