
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from fe import  *
from upload import *
from login import *
from pathlib import  Path
import sys, os, sqlite3, datetime
from shutil import rmtree
from apscheduler.schedulers.qt import QtScheduler
import datetime


class MainApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tabWidget.tabBar().setVisible(False)
        self.handle_button()
        self.connect()
        self.Show_all()
        
        self.scheduler = QtScheduler()
        self.setJob = 0

    def handle_button(self):
        self.ui.setfolder.clicked.connect(self.setDirection)
        self.ui.setcaption.clicked.connect(self.setDirection)
        self.ui.setfolder_3.clicked.connect(self.setDirection)
        self.ui.setcaption_3.clicked.connect(self.setDirection)
        self.ui.addsave.clicked.connect(self.Add_New)
        self.ui.refresh.clicked.connect(self.Show_all)
        self.ui.add.clicked.connect(self.tabAdd)
        self.ui.backadd.clicked.connect(self.back)
        self.ui.backedit.clicked.connect(self.back)
        self.ui.backedit_2.clicked.connect(self.back)
        self.ui.editsave.clicked.connect(self.Edit_user)
        self.ui.reup.clicked.connect(self.reup)
        self.ui.login.clicked.connect(self.login)
        self.ui.pushButton.clicked.connect(self.lenLich)
        self.ui.hengio.clicked.connect(self.henGio)
        self.ui.tabdown.clicked.connect(self.chonTab)
        self.ui.tabreup.clicked.connect(self.chonTab)

    def chonTab(self):
        but = self.sender()
        if but.objectName() == 'tabdown':
            self.ui.stackedWidget.setCurrentIndex(1)
        if but.objectName() == 'tabreup':
            self.ui.stackedWidget.setCurrentIndex(0)


    def reup(self):
        chedo = self.ui.comboBox.currentIndex()
        if chedo == 0:
            self.upload()
        else:
            self.runall()

    def runall(self):
        count = int(self.ui.tableWidget.rowCount())
        self.chayall = []
        for x in range(0, count-1):
            try:
                profile = self.ui.tableWidget.item(x, 2).text()
                folder = self.ui.tableWidget.item(x, 3).text()
                caption = self.ui.tableWidget.item(x, 4).text()
                soluong = int(self.ui.comboBox_3.currentText())
                
                if profile != '' and folder != '' and caption != '':
                    chayall = Upload(profile, folder, caption, soluong)
                    self.chayall.append(chayall)
                    chayall.stt.connect(self.stt)
                    chayall.start()
            except Exception as e:
                self.stt(str(e))
           

    def upload(self):
        try:
            r = self.ui.tableWidget.currentRow()
            profile = self.ui.tableWidget.item(r, 2).text()
            folder = self.ui.tableWidget.item(r, 3).text()
            caption = self.ui.tableWidget.item(r, 4).text()
            soluong = int(self.ui.comboBox_3.currentText())
            if profile != '' and folder != '' and caption != '':
                self.luong = Upload(profile, folder, caption, soluong)
                self.luong.stt.connect(self.stt)
                self.luong.start()
        except Exception as e:
            self.stt('Dữ liệu chọn không đúng')

    def henGio(self):
        self.ui.tabWidget.setCurrentIndex(3)
        self.ui.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
        _translate = QCoreApplication.translate
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * from user')
        data = cur.fetchall()
        for row, form in enumerate(data):
            self.ui.selectAcc.addItem(_translate("MainWindow", form[1]))
        conn.close()

    def chay(self, profile, folder, caption, soluong):
        self.uphen = Upload(profile, folder, caption, soluong)
        self.uphen.stt.connect(self.stt)
        self.uphen.start()
        self.ui.tableWidget_2.removeRow(0)

    def lenLich(self):
        taikhoan = self.ui.selectAcc.currentText()
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * FROM user WHERE tai_khoan = ?',(taikhoan,))
        data = cur.fetchone()
        timeup = self.ui.dateTimeEdit.dateTime()
        if datetime.datetime.now() < timeup.toPyDateTime():
            tgian = timeup.toPyDateTime().strftime('%H:%M %d/%m')
            soluong = int(self.ui.comboBox_6.currentText())
            rowCount = self.ui.tableWidget_2.rowCount()
            self.ui.tableWidget_2.insertRow(rowCount)
            self.ui.tableWidget_2.setItem(rowCount, 0, QTableWidgetItem(str(data[0])))
            self.ui.tableWidget_2.setItem(rowCount, 1, QTableWidgetItem(str(data[1])))
            self.ui.tableWidget_2.setItem(rowCount, 2, QTableWidgetItem(str(data[2])))
            self.ui.tableWidget_2.setItem(rowCount, 3, QTableWidgetItem(str(data[3])))
            self.ui.tableWidget_2.setItem(rowCount, 4, QTableWidgetItem(str(data[4])))
            self.ui.tableWidget_2.setItem(rowCount, 5, QTableWidgetItem(str(tgian)))
            self.ui.tableWidget_2.setItem(rowCount, 6, QTableWidgetItem(str(soluong)))

            
            self.scheduler.add_job(self.chay, 'date', next_run_time=timeup.toPyDateTime(), args=[data[2], data[3], data[4], soluong])
            # scheduler.add_job(tick, 'interval')
            if self.setJob == 0:
                self.scheduler.start()
                self.setJob = 1
        else:
            print('Bạn phải chọn thời gian lớn hơn hiện tại')



    def login(self):
        try:
            r = self.ui.tableWidget.currentRow()
            profile = self.ui.tableWidget.item(r, 2).text()
            sltime = int(self.ui.comboBox_2.currentText())
            self.dangnhap = Login(profile, sltime)
            self.dangnhap.start()
        except:
            self.stt('Bạn chưa chọn tài khoản')

    def stt(self, text):
        self.statusBar().showMessage(text)

    def back(self):
        self.ui.tabWidget.setCurrentIndex(0)

    def tabAdd(self):
        self.ui.tabWidget.setCurrentIndex(1)
    def connect(self):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute(
            'CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, tai_khoan text UNIQUE, profile text UNIQUE, folder text, caption text)')
        # cur.execute(
        #     'CREATE TABLE IF NOT EXISTS update_video (id INTEGER PRIMARY KEY, tai_khoan_vn text, tai_khoan_cn text, id_post_cn text)')
        # cur.execute(
        #     'CREATE TABLE IF NOT EXISTS user_post (id INTEGER PRIMARY KEY, id_post text, view_count integer, like_count integer, tai_khoan text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS setting_general (id INTEGER PRIMARY KEY, time_post text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS setting (id INTEGER PRIMARY KEY, time_post text, id_user text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS che_do (id INTEGER PRIMARY KEY, status text)')
        conn.commit()
        conn.close()

    def Add_New(self):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        taikhoan = self.ui.username.text()
        profile = self.ui.profile.text()
        folder = self.ui.folder.text()
        caption = self.ui.caption.text()
        if taikhoan == '':
            self.statusBar().showMessage('Tài khoản không được để trống')
            return 0
        if profile == '':
            self.statusBar().showMessage('Profile không được để trống')
            return 0
        if folder == '':
            self.statusBar().showMessage('Thư mục reup không được để trống')
            return 0
        if caption == '':
            self.statusBar().showMessage('Caption không được để trống')
            return 0
        try:
            cur.execute('INSERT INTO user(tai_khoan,profile,folder,caption) VALUES (?,?,?,?)',
                             (taikhoan, profile, folder, caption))
        except Exception as e:
            if 'tai_khoan' in str(e):
                self.statusBar().showMessage('Tài khoản này đã tồn tại')
            if 'profile' in str(e):
                self.statusBar().showMessage('Tên profile đã tồn tại')
            conn.commit()
            conn.close()
            return 0

        conn.commit()
        conn.close()
        self.Show_all()
        self.statusBar().showMessage('New user Added')
        self.ui.tabWidget.setCurrentIndex(0)

    def Show_all(self):
        self.ui.tableWidget.clearContents()
        self.ui.tableWidget.setRowCount(0)
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * from user')
        data = cur.fetchall()
        self.ui.tableWidget.insertRow(0)
        for row, form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
                column += 1
            self.btn_run = QPushButton('Edit')
            self.btn_run.clicked.connect(self.handleButtonClicked)
            self.ui.tableWidget.setCellWidget(row, 5, self.btn_run)
            self.btn_del = QPushButton('Del')
            self.btn_del.clicked.connect(self.handleButtonClicked)
            self.ui.tableWidget.setCellWidget(row, 6, self.btn_del)
            row_positon = self.ui.tableWidget.rowCount()
            self.ui.tableWidget.insertRow(row_positon)
        conn.close()

    def Edit_user(self):
        r = self.ui.tableWidget.currentRow()
        uid = self.ui.tableWidget.item(r, 0).text()
        taikhoan = self.ui.username_3.text()
        profile = self.ui.profile_3.text()
        folder = self.ui.folder_3.text()
        caption = self.ui.caption_3.text()
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute(
            'UPDATE user SET tai_khoan=?, profile=?, folder=?, caption=? WHERE id=?',
            (taikhoan, profile, folder, caption, uid))
        # self.cur.execute('UPDATE update_video SET tai_khoan_vn=?, tai_khoan_cn=? WHERE tai_khoan_vn=?',
        #                  (tai_khoan, tai_khoan_ru, tai_khoan))
        # if self.cur.rowcount == 0:
        #     self.cur.execute('INSERT INTO update_video(tai_khoan_vn,tai_khoan_cn) VALUES (?,?)',
        #                      (tai_khoan, tai_khoan_ru))
        conn.commit()
        conn.close()
        self.statusBar().showMessage('User Updated')
        self.Show_all()
        self.ui.tabWidget.setCurrentIndex(0)
        # self.Search_Books()

    def Delete_user(self, uid):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        try:
            cur.execute('DELETE FROM user WHERE id=?', (int(uid),))
            # rmtree('data/cookie/' + cookie)
        except:
            pass
        conn.commit()
        conn.close()
        self.statusBar().showMessage('User Deteted')


    def handleButtonClicked(self):
        button = QApplication.focusWidget()
        but = self.sender()
        index = self.ui.tableWidget.indexAt(button.pos())
        if index.isValid():

            if (index.column() == 5):
                self.ui.username_3.setText(self.ui.tableWidget.item(index.row(), 1).text())
                self.ui.profile_3.setText(self.ui.tableWidget.item(index.row(), 2).text())
                self.ui.folder_3.setText(self.ui.tableWidget.item(index.row(), 3).text())
                self.ui.caption_3.setText(self.ui.tableWidget.item(index.row(), 4).text())
                self.ui.tabWidget.setCurrentIndex(2)
                # folder = self.ui.folder.text()
                # limit = int(self.ui.limit.text())
                # cookie = self.ui.tableWidget.item(index.row(), 1).text()
                # self.thread = QThread()
                # self.ui.tableWidget.setItem(index.row(), 2, QTableWidgetItem("Running"))
                # obj = Reup(profile=1, limit=limit, folder=folder, cookie=cookie, row=index.row())
                # self.obj.moveToThread(self.thread)
                # self.thread.started.connect(self.obj.upload)
                # obj.fn.connect(self.ketthuc)
                # self.thread.append(obj)
                # obj.start()
                # self.obj.tq.connect(self.thread.quit)
                # self.thread.start()

            if (index.column() == 6):
                buttonReply = QMessageBox.question(self, 'Delete the account', "Do you want to delete this account?",
                                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if buttonReply == QMessageBox.Yes:
                    name = self.ui.tableWidget.item(index.row(), 0).text()
                    self.Delete_user(name)
                    self.ui.tableWidget.clearContents()
                    self.ui.tableWidget.setRowCount(0)
                    self.Show_all()



    def setDirection(self):
        btn = self.sender()
        if btn.objectName() == 'setfolder':

            path = str(Path().absolute())
            dir_ = QFileDialog.getExistingDirectory(self, "Select a folder", path, QFileDialog.ShowDirsOnly)
            if dir_:
                self.ui.folder.setText(str(dir_))
        if btn.objectName() == 'setfolder_3':

            path = str(Path().absolute())
            dir_ = QFileDialog.getExistingDirectory(self, "Select a folder", path, QFileDialog.ShowDirsOnly)
            if dir_:
                self.ui.folder_3.setText(str(dir_))

        if btn.objectName() == 'setcaption':

            path = str(Path().absolute())
            options = QFileDialog.Options()
            # options |= QFileDialog.DontUseNativeDialog
            fileName, _ = QFileDialog.getOpenFileName(self, "Select Caption File", "",
                                                      "Text Files (*.txt)")
            if fileName:
                self.ui.caption.setText(str(fileName))
        if btn.objectName() == 'setcaption_3':

            path = str(Path().absolute())
            options = QFileDialog.Options()
            # options |= QFileDialog.DontUseNativeDialog
            fileName, _ = QFileDialog.getOpenFileName(self, "Select Caption File", "",
                                                      "Text Files (*.txt)")
            if fileName:
                self.ui.caption_3.setText(str(fileName))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainApp()
    window.show()
    app.exec_()


from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from fe import  *
from upload import *
from login import *
from pathlib import  Path
import sys, os, sqlite3, datetime
from shutil import rmtree
from apscheduler.schedulers.qt import QtScheduler
import datetime


class MainApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.tabWidget.tabBar().setVisible(False)
        self.handle_button()
        self.connect()
        self.Show_all()
        
        self.scheduler = QtScheduler()
        self.setJob = 0

    def handle_button(self):
        self.ui.setfolder.clicked.connect(self.setDirection)
        self.ui.setcaption.clicked.connect(self.setDirection)
        self.ui.setfolder_3.clicked.connect(self.setDirection)
        self.ui.setcaption_3.clicked.connect(self.setDirection)
        self.ui.addsave.clicked.connect(self.Add_New)
        self.ui.refresh.clicked.connect(self.Show_all)
        self.ui.add.clicked.connect(self.tabAdd)
        self.ui.backadd.clicked.connect(self.back)
        self.ui.backedit.clicked.connect(self.back)
        self.ui.backedit_2.clicked.connect(self.back)
        self.ui.editsave.clicked.connect(self.Edit_user)
        self.ui.reup.clicked.connect(self.reup)
        self.ui.login.clicked.connect(self.login)
        self.ui.pushButton.clicked.connect(self.lenLich)
        self.ui.hengio.clicked.connect(self.henGio)
        self.ui.tabdown.clicked.connect(self.chonTab)
        self.ui.tabreup.clicked.connect(self.chonTab)

    def chonTab(self):
        but = self.sender()
        if but.objectName() == 'tabdown':
            self.ui.stackedWidget.setCurrentIndex(1)
        if but.objectName() == 'tabreup':
            self.ui.stackedWidget.setCurrentIndex(0)


    def reup(self):
        chedo = self.ui.comboBox.currentIndex()
        if chedo == 0:
            self.upload()
        else:
            self.runall()

    def runall(self):
        count = int(self.ui.tableWidget.rowCount())
        self.chayall = []
        for x in range(0, count-1):
            try:
                profile = self.ui.tableWidget.item(x, 2).text()
                folder = self.ui.tableWidget.item(x, 3).text()
                caption = self.ui.tableWidget.item(x, 4).text()
                soluong = int(self.ui.comboBox_3.currentText())
                
                if profile != '' and folder != '' and caption != '':
                    chayall = Upload(profile, folder, caption, soluong)
                    self.chayall.append(chayall)
                    chayall.stt.connect(self.stt)
                    chayall.start()
            except Exception as e:
                self.stt(str(e))
           

    def upload(self):
        try:
            r = self.ui.tableWidget.currentRow()
            profile = self.ui.tableWidget.item(r, 2).text()
            folder = self.ui.tableWidget.item(r, 3).text()
            caption = self.ui.tableWidget.item(r, 4).text()
            soluong = int(self.ui.comboBox_3.currentText())
            if profile != '' and folder != '' and caption != '':
                self.luong = Upload(profile, folder, caption, soluong)
                self.luong.stt.connect(self.stt)
                self.luong.start()
        except Exception as e:
            self.stt('Dữ liệu chọn không đúng')

    def henGio(self):
        self.ui.tabWidget.setCurrentIndex(3)
        self.ui.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
        _translate = QCoreApplication.translate
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * from user')
        data = cur.fetchall()
        for row, form in enumerate(data):
            self.ui.selectAcc.addItem(_translate("MainWindow", form[1]))
        conn.close()

    def chay(self, profile, folder, caption, soluong):
        self.uphen = Upload(profile, folder, caption, soluong)
        self.uphen.stt.connect(self.stt)
        self.uphen.start()
        self.ui.tableWidget_2.removeRow(0)

    def lenLich(self):
        taikhoan = self.ui.selectAcc.currentText()
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * FROM user WHERE tai_khoan = ?',(taikhoan,))
        data = cur.fetchone()
        timeup = self.ui.dateTimeEdit.dateTime()
        if datetime.datetime.now() < timeup.toPyDateTime():
            tgian = timeup.toPyDateTime().strftime('%H:%M %d/%m')
            soluong = int(self.ui.comboBox_6.currentText())
            rowCount = self.ui.tableWidget_2.rowCount()
            self.ui.tableWidget_2.insertRow(rowCount)
            self.ui.tableWidget_2.setItem(rowCount, 0, QTableWidgetItem(str(data[0])))
            self.ui.tableWidget_2.setItem(rowCount, 1, QTableWidgetItem(str(data[1])))
            self.ui.tableWidget_2.setItem(rowCount, 2, QTableWidgetItem(str(data[2])))
            self.ui.tableWidget_2.setItem(rowCount, 3, QTableWidgetItem(str(data[3])))
            self.ui.tableWidget_2.setItem(rowCount, 4, QTableWidgetItem(str(data[4])))
            self.ui.tableWidget_2.setItem(rowCount, 5, QTableWidgetItem(str(tgian)))
            self.ui.tableWidget_2.setItem(rowCount, 6, QTableWidgetItem(str(soluong)))

            
            self.scheduler.add_job(self.chay, 'date', next_run_time=timeup.toPyDateTime(), args=[data[2], data[3], data[4], soluong])
            # scheduler.add_job(tick, 'interval')
            if self.setJob == 0:
                self.scheduler.start()
                self.setJob = 1
        else:
            print('Bạn phải chọn thời gian lớn hơn hiện tại')



    def login(self):
        try:
            r = self.ui.tableWidget.currentRow()
            profile = self.ui.tableWidget.item(r, 2).text()
            sltime = int(self.ui.comboBox_2.currentText())
            self.dangnhap = Login(profile, sltime)
            self.dangnhap.start()
        except:
            self.stt('Bạn chưa chọn tài khoản')

    def stt(self, text):
        self.statusBar().showMessage(text)

    def back(self):
        self.ui.tabWidget.setCurrentIndex(0)

    def tabAdd(self):
        self.ui.tabWidget.setCurrentIndex(1)
    def connect(self):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute(
            'CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, tai_khoan text UNIQUE, profile text UNIQUE, folder text, caption text)')
        # cur.execute(
        #     'CREATE TABLE IF NOT EXISTS update_video (id INTEGER PRIMARY KEY, tai_khoan_vn text, tai_khoan_cn text, id_post_cn text)')
        # cur.execute(
        #     'CREATE TABLE IF NOT EXISTS user_post (id INTEGER PRIMARY KEY, id_post text, view_count integer, like_count integer, tai_khoan text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS setting_general (id INTEGER PRIMARY KEY, time_post text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS setting (id INTEGER PRIMARY KEY, time_post text, id_user text)')
        # cur.execute('CREATE TABLE IF NOT EXISTS che_do (id INTEGER PRIMARY KEY, status text)')
        conn.commit()
        conn.close()

    def Add_New(self):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        taikhoan = self.ui.username.text()
        profile = self.ui.profile.text()
        folder = self.ui.folder.text()
        caption = self.ui.caption.text()
        if taikhoan == '':
            self.statusBar().showMessage('Tài khoản không được để trống')
            return 0
        if profile == '':
            self.statusBar().showMessage('Profile không được để trống')
            return 0
        if folder == '':
            self.statusBar().showMessage('Thư mục reup không được để trống')
            return 0
        if caption == '':
            self.statusBar().showMessage('Caption không được để trống')
            return 0
        try:
            cur.execute('INSERT INTO user(tai_khoan,profile,folder,caption) VALUES (?,?,?,?)',
                             (taikhoan, profile, folder, caption))
        except Exception as e:
            if 'tai_khoan' in str(e):
                self.statusBar().showMessage('Tài khoản này đã tồn tại')
            if 'profile' in str(e):
                self.statusBar().showMessage('Tên profile đã tồn tại')
            conn.commit()
            conn.close()
            return 0

        conn.commit()
        conn.close()
        self.Show_all()
        self.statusBar().showMessage('New user Added')
        self.ui.tabWidget.setCurrentIndex(0)

    def Show_all(self):
        self.ui.tableWidget.clearContents()
        self.ui.tableWidget.setRowCount(0)
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute('SELECT * from user')
        data = cur.fetchall()
        self.ui.tableWidget.insertRow(0)
        for row, form in enumerate(data):
            for column, item in enumerate(form):
                self.ui.tableWidget.setItem(row, column, QTableWidgetItem(str(item)))
                column += 1
            self.btn_run = QPushButton('Edit')
            self.btn_run.clicked.connect(self.handleButtonClicked)
            self.ui.tableWidget.setCellWidget(row, 5, self.btn_run)
            self.btn_del = QPushButton('Del')
            self.btn_del.clicked.connect(self.handleButtonClicked)
            self.ui.tableWidget.setCellWidget(row, 6, self.btn_del)
            row_positon = self.ui.tableWidget.rowCount()
            self.ui.tableWidget.insertRow(row_positon)
        conn.close()

    def Edit_user(self):
        r = self.ui.tableWidget.currentRow()
        uid = self.ui.tableWidget.item(r, 0).text()
        taikhoan = self.ui.username_3.text()
        profile = self.ui.profile_3.text()
        folder = self.ui.folder_3.text()
        caption = self.ui.caption_3.text()
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        cur.execute(
            'UPDATE user SET tai_khoan=?, profile=?, folder=?, caption=? WHERE id=?',
            (taikhoan, profile, folder, caption, uid))
        # self.cur.execute('UPDATE update_video SET tai_khoan_vn=?, tai_khoan_cn=? WHERE tai_khoan_vn=?',
        #                  (tai_khoan, tai_khoan_ru, tai_khoan))
        # if self.cur.rowcount == 0:
        #     self.cur.execute('INSERT INTO update_video(tai_khoan_vn,tai_khoan_cn) VALUES (?,?)',
        #                      (tai_khoan, tai_khoan_ru))
        conn.commit()
        conn.close()
        self.statusBar().showMessage('User Updated')
        self.Show_all()
        self.ui.tabWidget.setCurrentIndex(0)
        # self.Search_Books()

    def Delete_user(self, uid):
        conn = sqlite3.connect('books.db')
        cur = conn.cursor()
        try:
            cur.execute('DELETE FROM user WHERE id=?', (int(uid),))
            # rmtree('data/cookie/' + cookie)
        except:
            pass
        conn.commit()
        conn.close()
        self.statusBar().showMessage('User Deteted')


    def handleButtonClicked(self):
        button = QApplication.focusWidget()
        but = self.sender()
        index = self.ui.tableWidget.indexAt(button.pos())
        if index.isValid():

            if (index.column() == 5):
                self.ui.username_3.setText(self.ui.tableWidget.item(index.row(), 1).text())
                self.ui.profile_3.setText(self.ui.tableWidget.item(index.row(), 2).text())
                self.ui.folder_3.setText(self.ui.tableWidget.item(index.row(), 3).text())
                self.ui.caption_3.setText(self.ui.tableWidget.item(index.row(), 4).text())
                self.ui.tabWidget.setCurrentIndex(2)
                # folder = self.ui.folder.text()
                # limit = int(self.ui.limit.text())
                # cookie = self.ui.tableWidget.item(index.row(), 1).text()
                # self.thread = QThread()
                # self.ui.tableWidget.setItem(index.row(), 2, QTableWidgetItem("Running"))
                # obj = Reup(profile=1, limit=limit, folder=folder, cookie=cookie, row=index.row())
                # self.obj.moveToThread(self.thread)
                # self.thread.started.connect(self.obj.upload)
                # obj.fn.connect(self.ketthuc)
                # self.thread.append(obj)
                # obj.start()
                # self.obj.tq.connect(self.thread.quit)
                # self.thread.start()

            if (index.column() == 6):
                buttonReply = QMessageBox.question(self, 'Delete the account', "Do you want to delete this account?",
                                                   QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if buttonReply == QMessageBox.Yes:
                    name = self.ui.tableWidget.item(index.row(), 0).text()
                    self.Delete_user(name)
                    self.ui.tableWidget.clearContents()
                    self.ui.tableWidget.setRowCount(0)
                    self.Show_all()



    def setDirection(self):
        btn = self.sender()
        if btn.objectName() == 'setfolder':

            path = str(Path().absolute())
            dir_ = QFileDialog.getExistingDirectory(self, "Select a folder", path, QFileDialog.ShowDirsOnly)
            if dir_:
                self.ui.folder.setText(str(dir_))
        if btn.objectName() == 'setfolder_3':

            path = str(Path().absolute())
            dir_ = QFileDialog.getExistingDirectory(self, "Select a folder", path, QFileDialog.ShowDirsOnly)
            if dir_:
                self.ui.folder_3.setText(str(dir_))

        if btn.objectName() == 'setcaption':

            path = str(Path().absolute())
            options = QFileDialog.Options()
            # options |= QFileDialog.DontUseNativeDialog
            fileName, _ = QFileDialog.getOpenFileName(self, "Select Caption File", "",
                                                      "Text Files (*.txt)")
            if fileName:
                self.ui.caption.setText(str(fileName))
        if btn.objectName() == 'setcaption_3':

            path = str(Path().absolute())
            options = QFileDialog.Options()
            # options |= QFileDialog.DontUseNativeDialog
            fileName, _ = QFileDialog.getOpenFileName(self, "Select Caption File", "",
                                                      "Text Files (*.txt)")
            if fileName:
                self.ui.caption_3.setText(str(fileName))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainApp()
    window.show()
    app.exec_()

# scheduler.add_job(tick, 'interval') # cur.execute( #     'CREATE TABLE IF NOT EXISTS update_video (id INTEGER PRIMARY KEY, tai_khoan_vn text, tai_khoan_cn text, id_post_cn text)') # cur.execute( #     'CREATE TABLE IF NOT EXISTS user_post (id INTEGER PRIMARY KEY, id_post text, view_count integer, like_count integer, tai_khoan text)') # cur.execute('CREATE TABLE IF NOT EXISTS setting_general (id INTEGER PRIMARY KEY, time_post text)') # cur.execute('CREATE TABLE IF NOT EXISTS setting (id INTEGER PRIMARY KEY, time_post text, id_user text)') # cur.execute('CREATE TABLE IF NOT EXISTS che_do (id INTEGER PRIMARY KEY, status text)') # self.cur.execute('UPDATE update_video SET tai_khoan_vn=?, tai_khoan_cn=? WHERE tai_khoan_vn=?', #                  (tai_khoan, tai_khoan_ru, tai_khoan)) # if self.cur.rowcount == 0: #     self.cur.execute('INSERT INTO update_video(tai_khoan_vn,tai_khoan_cn) VALUES (?,?)', #                      (tai_khoan, tai_khoan_ru)) # self.Search_Books() # rmtree('data/cookie/' + cookie) # folder = self.ui.folder.text() # limit = int(self.ui.limit.text()) # cookie = self.ui.tableWidget.item(index.row(), 1).text() # self.thread = QThread() # self.ui.tableWidget.setItem(index.row(), 2, QTableWidgetItem("Running")) # obj = Reup(profile=1, limit=limit, folder=folder, cookie=cookie, row=index.row()) # self.obj.moveToThread(self.thread) # self.thread.started.connect(self.obj.upload) # obj.fn.connect(self.ketthuc) # self.thread.append(obj) # obj.start() # self.obj.tq.connect(self.thread.quit) # self.thread.start() # options |= QFileDialog.DontUseNativeDialog # options |= QFileDialog.DontUseNativeDialog