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

# Form implementation generated from reading ui file 'c:\Users\Hritish\Documents\python\discord-autosend\gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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 sys
from PyQt5 import QtCore, QtGui, QtWidgets
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from time import sleep
from pickle import load, dump

try:
    from PyQt5.QtWinExtras import QtWin
    myappid = 'hritish.discord.autosend.1.0'
    QtWin.setCurrentProcessExplicitAppUserModelID(myappid)
except ImportError:
    pass

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(620, 380)
        MainWindow.setStyleSheet("background-color: rgb(44, 47, 51);\n"
"color: rgb(255, 255, 255);\n"
"alternate-background-color: rgb(35, 39, 42);")
        MainWindow.setUnifiedTitleAndToolBarOnMac(True)
        MainWindow.setWindowIcon(QtGui.QIcon(":/image/logo1.ico"))

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.email_label = QtWidgets.QLabel(self.centralwidget)
        self.email_label.setGeometry(QtCore.QRect(40, 101, 221, 16))
        self.email_label.setObjectName("email_label")
        self.email = QtWidgets.QLineEdit(self.centralwidget)
        self.email.setGeometry(QtCore.QRect(192, 101, 391, 25))
        self.email.setObjectName("email")


        self.passwd_label = QtWidgets.QLabel(self.centralwidget)
        self.passwd_label.setGeometry(QtCore.QRect(40, 131, 231, 16))
        self.passwd_label.setObjectName("passwd_label")
        self.passwd = QtWidgets.QLineEdit(self.centralwidget)
        self.passwd.setGeometry(QtCore.QRect(192, 131, 291, 25))
        self.passwd.setObjectName("passwd")
        self.passwd.setEchoMode(QtWidgets.QLineEdit.Password)
        self.passwd.setStyleSheet('lineedit-password-character: 9679')

        self.save_passwd = QtWidgets.QPushButton(self.centralwidget)
        self.save_passwd.setEnabled(True)
        self.save_passwd.setGeometry(QtCore.QRect(490, 131, 91, 25))
        self.save_passwd.setAutoFillBackground(False)
        self.save_passwd.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(44, 47, 51);")
        self.save_passwd.setObjectName("save_passwd")

        self.save_passwd.clicked.connect(self.store)
        
        
        self.link_label = QtWidgets.QLabel(self.centralwidget)
        self.link_label.setGeometry(QtCore.QRect(38, 171, 231, 20))
        self.link_label.setObjectName("link_label")
        self.link = QtWidgets.QLineEdit(self.centralwidget)
        self.link.setGeometry(QtCore.QRect(230, 171, 351, 25))
        self.link.setObjectName("link")
        self.link.setText("")


        self.message_label = QtWidgets.QLabel(self.centralwidget)
        self.message_label.setGeometry(QtCore.QRect(38, 201, 221, 20))
        self.message_label.setObjectName("message_label")
        self.message = QtWidgets.QLineEdit(self.centralwidget)
        self.message.setGeometry(QtCore.QRect(230, 201, 351, 25))
        self.message.setObjectName("message")
        self.message.setText("")


        self.progressbar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressbar.setGeometry(QtCore.QRect(40, 331, 541, 23))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.progressbar.sizePolicy().hasHeightForWidth())
        self.progressbar.setSizePolicy(sizePolicy)
        self.progressbar.setMaximum(0)
        self.progressbar.setProperty("value", 0)
        self.progressbar.setTextVisible(True)
        self.progressbar.setInvertedAppearance(False)
        self.progressbar.setTextDirection(QtWidgets.QProgressBar.TopToBottom)
        self.progressbar.setFormat(" %p% [%v / %m messages sent]")
        self.progressbar.setObjectName("progressbar")
        

        self.number_label = QtWidgets.QLabel(self.centralwidget)
        self.number_label.setGeometry(QtCore.QRect(40, 231, 351, 20))
        self.number_label.setObjectName("number_label")
        self.number = QtWidgets.QSpinBox(self.centralwidget)
        self.number.setGeometry(QtCore.QRect(400, 231, 181, 22))
        self.number.setAccelerated(True)
        self.number.setMinimum(1)
        self.number.setMaximum(999999999)
        self.number.setSingleStep(1)
        self.number.setObjectName("number")
        self.number.setValue(10)
        

        self.interval = QtWidgets.QSpinBox(self.centralwidget)
        self.interval.setGeometry(QtCore.QRect(400, 261, 181, 22))
        self.interval.setAccelerated(True)
        self.interval.setMinimum(1)
        self.interval.setMaximum(999999999)
        self.interval.setSingleStep(1)
        self.interval.setObjectName("interval")
        self.interval_label = QtWidgets.QLabel(self.centralwidget)
        self.interval_label.setGeometry(QtCore.QRect(40, 261, 351, 20))
        self.interval_label.setObjectName("interval_label")

        
        self.browser_label = QtWidgets.QLabel(self.centralwidget)
        self.browser_label.setGeometry(QtCore.QRect(40, 290, 151, 20))
        self.browser_label.setObjectName("browser_label")
        self.browser = QtWidgets.QComboBox(self.centralwidget)
        self.browser.setGeometry(QtCore.QRect(230, 290, 250, 25))
        self.browser.setStyleSheet("border-color: rgb(255, 255, 255);")
        self.browser.setObjectName("browser")
        self.browser.addItem("")
        self.browser.addItem("")
        self.browser.addItem("")


        self.start = QtWidgets.QPushButton(self.centralwidget)
        self.start.setEnabled(True)
        self.start.setGeometry(QtCore.QRect(490, 290, 90, 25))
        self.start.setAutoFillBackground(False)
        self.start.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"color: rgb(44, 47, 51);")
        self.start.setObjectName("start")

        self.start.clicked.connect(self.startblock)


        self.result = QtWidgets.QLabel(self.centralwidget)
        self.result.setEnabled(True)
        self.result.setGeometry(QtCore.QRect(40, 355, 400, 20))
        self.result.setFocusPolicy(QtCore.Qt.NoFocus)
        self.result.setText("Ready")
        self.result.setAlignment(QtCore.Qt.AlignCenter)
        self.result.setObjectName("result")


        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 10, 621, 81))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap(":/image/logo.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Discord Autosend"))
        self.link_label.setText(_translate("MainWindow", "Enter channel link :"))
        self.message_label.setText(_translate("MainWindow", "Enter message :"))
        self.number_label.setText(_translate("MainWindow", "Enter number of messages :"))
        self.save_passwd.setText(_translate("MainWindow", "Save"))
        self.passwd_label.setText(_translate("MainWindow", "Password :"))
        self.email_label.setText(_translate("MainWindow", "Discord Email :"))
        self.interval_label.setText(_translate("MainWindow", "Enter message interval (seconds)  :"))
        self.start.setText(_translate("MainWindow", "Start"))
        self.browser_label.setText(_translate("MainWindow", "Select browser  :"))
        self.browser.setItemText(0, _translate("MainWindow", "Google Chrome"))
        self.browser.setItemText(1, _translate("MainWindow", "Microsoft Edge"))
        self.browser.setItemText(2, _translate("MainWindow", "Mozilla Firefox"))
    
    def retrieve(self):
        try:
            frobj = open("logindetails.dat","rb")
            details = load(frobj)
            frobj.close()
            return details
        except:
            return None
    
    def store(self):
        email = self.email.text()
        passwd = self.passwd.text()
        fwobj = open("logindetails.dat","wb")
        dump((email,passwd),fwobj)
        fwobj.close()
        ui.result.setText("Login stored successfully")
        sleep(1)
    
    def startup(self):
        details = self.retrieve()
        if (details != None):
            email,passwd = details
        else:
            email,passwd = ('','')
        ui.email.setText(email)
        ui.passwd.setText(passwd)

    def startblock(self):
        ui.email.setDisabled(True)
        ui.passwd.setDisabled(True)
        ui.link.setDisabled(True)
        ui.message.setDisabled(True)
        ui.number.setDisabled(True)
        ui.interval.setDisabled(True)
        ui.browser.setDisabled(True)
        self.main()

    def main(self):
        self.thread = QtCore.QThread()
        self.worker = SeleniumWorker()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.start()
        self.worker.progressChanged.connect(self.progressbar.setValue, QtCore.Qt.QueuedConnection)

    def endblock(self):
        ui.email.setEnabled(True)
        ui.passwd.setEnabled(True)
        ui.link.setEnabled(True)
        ui.message.setEnabled(True)
        ui.number.setEnabled(True)
        ui.interval.setEnabled(True)
        ui.browser.setEnabled(True)


class SeleniumWorker(QtCore.QThread):
    progressChanged = QtCore.pyqtSignal(int)
    def __init__(self):
        QtCore.QThread.__init__(self)
    
    def __del__(self):
        self.wait()

    def run(self):
        global driver, flag, templink, tempbrowser
        email = ui.email.text()
        passwd = ui.passwd.text()
        link = ui.link.text()
        message = ui.message.text()
        n = ui.number.value()
        interval = ui.interval.value()
        browser = ui.browser.currentText()

        ui.result.setText("Setting up browser...")
        
        if (browser != tempbrowser):
            if (browser == "Google Chrome"):
                driver = webdriver.Chrome(ChromeDriverManager().install())
            elif (browser == "Microsoft Edge"):
                driver = webdriver.Edge(EdgeChromiumDriverManager().install())
            elif (browser == "Mozilla Firefox"):
                driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
            templink = ''
        
        if (link != templink):
            ui.result.setText("Loading Discord...")
            driver.get(link)
            templink = link
        
        if (browser != tempbrowser):
            myElem = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.NAME , 'email')))
            ui.result.setText("Logging in...")
            driver.find_element_by_name('email').send_keys(email)
            driver.find_element_by_name('password').send_keys(passwd)
            driver.find_element_by_name('password').send_keys(Keys.RETURN)
            sleep(5)
            ui.result.setText("Logged in successfully")
            tempbrowser = browser
        sleep(1)

        myElem = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID , 'svg-mask-panel-button')))
        ui.result.setText("Sending messages...")
        
        ui.progressbar.setMaximum(n)

        for i in range(n):
            sleep(interval)
            actions = ActionChains(driver)
            actions.send_keys(message)
            actions.send_keys(Keys.ENTER)
            actions.perform()
            self.progressChanged.emit(i + 1)
            
        else:
            ui.result.setText("All Messages Sent")
            ui.endblock()


import logo_rc
if __name__ == "__main__":
    import sys
    flag = False
    templink = ''
    driver = ''
    tempbrowser = ''
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
