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

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


from PySide2 import QtCore, QtGui, QtWidgets
from math import floor
from redditScrape import scrape
from urllib.request import urlretrieve
import os


class Ui_MainWindow(QtWidgets.QWidget):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("nasa.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.row = 0
        self.col = 0
        self.buttons = []
        self.labels = []
        self.names = []
        self.verticals = []
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton1 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton1.setGeometry(QtCore.QRect(10, 10, 200, 28))
        self.pushButton1.setObjectName("pushButton1")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setGeometry(QtCore.QRect(50, 50, 700, 500))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 299, 219))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.gridLayout = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout.setObjectName("gridLayout")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setEnabled(True)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.pixmap = QtGui.QPixmap.scaled(QtGui.QPixmap("nasa.ico"), 100, 100)
        self.icons = []
        self.retranslateUi(MainWindow)
        self.pushButton1.clicked.connect(self.showMsgBox)
        user = os.getlogin()
        self.path = r'C:\Users\{}\Wallpaper test'.format(user)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def showMsgBox(self):
        MsgBox()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Wallpaper changer"))
        self.pushButton1.setText(_translate("MainWindow", "Add folder or subreddit"))

    def add(self):
        self.verticals.append(QtWidgets.QVBoxLayout())
        btn_temp = QtWidgets.QPushButton()
        btn_temp.setFlat(True)
        self.labels.append(btn_temp)
        self.names.append(QtWidgets.QLabel())
        self.buttons.append(QtWidgets.QPushButton(self.scrollAreaWidgetContents))
        self.labels[-1].setObjectName("pic" + str(self.row) + "," + str(self.col))
        self.labels[-1].setFixedWidth(100)
        self.labels[-1].setFixedHeight(100)
        self.names[-1].setObjectName("name" + str(self.row) + "," + str(self.col))
        self.names[-1].setFixedWidth(100)
        self.names[-1].setFixedHeight(50)
        self.buttons[-1].setObjectName("btn" + str(self.row) + "," + str(self.col))
        self.buttons[-1].setFixedWidth(100)
        self.buttons[-1].setFixedHeight(30)
        self.gridLayout.addLayout(self.verticals[-1], self.row, self.col)
        self.verticals[-1].addWidget(self.names[-1])
        self.names[-1].setAlignment(QtCore.Qt.AlignBottom | QtCore.Qt.AlignHCenter)
        self.verticals[-1].addWidget(self.labels[-1])
        self.verticals[-1].addWidget(self.buttons[-1])

        if self.col < 3:
            self.col += 1
        else:
            self.row += 1
            self.col = 0

        _translate = QtCore.QCoreApplication.translate
        self.labels[-1].setIcon(self.icons[-1][1])
        self.labels[-1].setIconSize(QtCore.QSize(100, 100))
        self.names[-1].setText(self.icons[-1][0])
        self.buttons[-1].clicked.connect(self.remove)
        self.buttons[-1].setText(_translate("MainWindow", "Remove"))

    def remove(self):
        sender = self.sender()
        index = self.buttons.index(sender)
        self.reorder(index)

    def reorder(self, index):
        # if removing last
        if index + 1 == len(self.buttons):
            if index == 3 or (index > 3 and (index + 1) % 4 == 0):
                self.row -= 1
                self.col = 3
            else:
                self.col -= 1

        # if removing some other
        else:
            for i in range(index, len(self.buttons)):
                if i == index:
                    pass
                else:
                    column = i % 4
                    row = floor(i / 4)
                    self.gridLayout.removeItem(self.verticals[i])
                    self.verticals[-1].removeWidget(self.buttons[i])
                    self.verticals[-1].removeWidget(self.labels[i])
                    self.verticals[-1].removeWidget(self.names[i])
                    if column == 0:
                        self.gridLayout.addLayout(self.verticals[i], row - 1, 3)
                    else:
                        self.gridLayout.addLayout(self.verticals[i], row, column - 1)

                    self.verticals[i].addWidget(self.names[i])
                    self.verticals[i].addWidget(self.labels[i])
                    self.verticals[i].addWidget(self.buttons[i])

            last = len(self.buttons)
            if last % 4 == 0:
                self.row -= 1
                self.col = 3
            else:
                self.col -= 1

        self.verticals[index].deleteLater()
        del self.verticals[index]
        self.buttons[index].deleteLater()
        del self.buttons[index]
        self.labels[index].deleteLater()
        del self.labels[index]
        self.names[index].deleteLater()
        del self.names[index]


class MsgBox(Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.msg = QtWidgets.QDialog(None,
                                     QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowCloseButtonHint)
        self.msg.setFixedHeight(400)
        self.msg.setFixedWidth(500)

        self.pixmap = QtGui.QPixmap.scaled(QtGui.QPixmap("nasa.ico"), 100, 100)

        self.infotext1 = QtWidgets.QLabel(self.msg)
        self.infotext1.setGeometry(QtCore.QRect(0, 10, 500, 28))
        self.infotext1.setFont(QtGui.QFont("Times", 9))
        self.infotext1.setAlignment(QtCore.Qt.AlignCenter)
        self.infotext1.setText("<b>To add a subreddit use full url to or use ending after reddit.com/r/</b>")

        self.infotext2 = QtWidgets.QLabel(self.msg)
        self.infotext2.setGeometry(QtCore.QRect(0, 30, 500, 28))
        self.infotext2.setText("<b>To add a directory please use full path</b>")
        self.infotext2.setAlignment(QtCore.Qt.AlignCenter)
        self.infotext2.setFont(QtGui.QFont("Times", 9))

        self.infotext3 = QtWidgets.QLabel(self.msg)
        self.infotext3.setGeometry(QtCore.QRect(0, 70, 500, 28))
        self.infotext3.setText("<b>Use enter to confirm path</b>")
        self.infotext3.setAlignment(QtCore.Qt.AlignCenter)
        self.infotext3.setFont(QtGui.QFont("Times", 9))

        self.txtdialog = QtWidgets.QLineEdit(self.msg)
        self.txtdialog.setGeometry(QtCore.QRect(40, 100, 400, 28))
        self.txtdialog.setPlaceholderText("Write url or directory path")
        self.txtdialog.setClearButtonEnabled(True)

        self.horizontalLayoutWidget = QtWidgets.QWidget(self.msg)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 120, 400, 200))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)

        self.previewPic1 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.previewPic1.setFixedWidth(100)
        self.previewPic1.setFixedHeight(100)
        self.previewPic1.setFlat(True)

        self.previewPic2 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.previewPic2.setFixedWidth(100)
        self.previewPic2.setFixedHeight(100)
        self.previewPic2.setFlat(True)

        self.horizontalLayout.addWidget(self.previewPic1)
        self.horizontalLayout.addWidget(self.previewPic2)
        self.horizontalLayout.setSpacing(80)

        self.radioButton1 = QtWidgets.QRadioButton(self.msg)
        self.radioButton1.move(128, 280)
        self.radioButton2 = QtWidgets.QRadioButton(self.msg)
        self.radioButton2.move(340, 280)

        self.pushButton3 = QtWidgets.QPushButton(self.msg)
        self.pushButton3.setText("Add to library")
        self.pushButton3.move(200, 350)

        self.pushButton4 = QtWidgets.QPushButton(self.msg)
        self.pushButton4.setText("Cancel")
        self.pushButton4.move(380, 350)

        self.previewPic1.hide()
        self.previewPic2.hide()
        self.radioButton1.hide()
        self.radioButton2.hide()

        self.txtdialog.editingFinished.connect(self.showPreview)
        self.repeater = False
        self.previewPic1.clicked.connect(self.radioButton1.animateClick)
        self.previewPic2.clicked.connect(self.radioButton2.animateClick)
        self.pushButton3.clicked.connect(self.addNew)
        self.pushButton4.clicked.connect(self.msg.reject)

        self.msg.setWindowTitle("Add a subreddit or directory")
        self.msg.setWindowIcon(self.pixmap)

        x = self.msg.exec_()

    def showPreview(self):
        if self.repeater == True:
            return 0
        else:
            self.temp_icons = self.getInfo(self.txtdialog.text(),ui.path)
            if self.temp_icons == 0:
                return 0
            self.radioButton1.move(128, 280)
            self.icon1 = QtGui.QIcon()
            cache_path = ui.path + '\\cache\\'
            path = cache_path+ self.temp_icons[0]+"\\"+self.temp_icons[1]
            self.icon1.addPixmap(QtGui.QPixmap(cache_path+self.temp_icons[1]), QtGui.QIcon.Normal, QtGui.QIcon.Off)
            self.previewPic1.setIcon(self.icon1)
            self.previewPic1.setIconSize(QtCore.QSize(100, 100))
            self.previewPic1.show()
            self.radioButton1.show()

            if len(self.temp_icons)==3:
                self.icon2 = QtGui.QIcon()
                self.icon2.addPixmap(QtGui.QPixmap(cache_path+ self.temp_icons[2]), QtGui.QIcon.Normal,
                                     QtGui.QIcon.Off)
                self.previewPic2.setIcon(self.icon2)
                self.previewPic2.setIconSize(QtCore.QSize(100, 100))
                self.previewPic2.show()
                self.radioButton2.show()

            else:
                self.radioButton1.move(235,280)




    def getInfo(self,text,path):
        scrap = scrape(text)

        if isinstance(scrap,int):
            print("err")
            return 0
        if isinstance(scrap,list):
            cache_path = path + '\cache'
            if scrap[0] == "url":
                try:
                    os.mkdir(path)
                    os.mkdir(cache_path)
                except OSError:
                    if os.path.exists(path):
                        # print("main dir užje")
                        try:
                            os.mkdir(cache_path)
                        except OSError:
                            if os.path.exists(cache_path):
                                pass
                                # print("cache dir už je")
                            else:
                                pass
                                # print('cache dir perm err')
                    else:
                        pass
                        # print("asi main dir permis err")

                os.chdir(cache_path)
                #top post preview
                if not os.path.isfile(scrap[1][0]+"-icon1.jpg"):
                    urlretrieve(scrap[1][1], scrap[1][0] + "-icon1.jpg")
                else:
                    pass
                #icon preview
                if not os.path.isfile(scrap[1][0]+"-icon2.jpg"):
                    if scrap[1][2]:
                        urlretrieve(scrap[1][2], scrap[1][0] + "-icon2.jpg")
                    else:
                        return [scrap[1][0], scrap[1][0] + "-icon1.jpg"]

            self.repeater = True

            return [scrap[1][0], scrap[1][0]+"-icon1.jpg",scrap[1][0]+"-icon2.jpg"]

    def addNew(self):
        if self.radioButton1.isChecked():
            ui.icons.append([self.temp_icons[0],QtGui.QPixmap(self.temp_icons[0]+"\\"+self.temp_icons[1])])
        elif self.radioButton2.isChecked():
            ui.icons.append([self.temp_icons[0],QtGui.QPixmap(self.temp_icons[0]+"\\"+self.temp_icons[2])])
        ui.add()
        self.msg.accept()



if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
