class CustomerWindow(QWidget):
    def __init__(self, db_connection, customer_name):
        super().__init__()
        self.customer_name = customer_name
        self.db_connection = db_connection
        self.create_window()

    def create_window(self):
        self.setGeometry(300, 300, 600, 300)  #x, y, w, h
        self.setWindowTitle('3D Printers DB - Logged as: ')

        self.main_layout = QHBoxLayout(self)
        self.create_menu()

        self.menu_spacer = QSpacerItem(40, 10)
        self.main_layout.addItem(self.menu_spacer)

        self.create_welcome_message_layout()
        self.create_customer_profile_layout()
        self.create_order_history_layout()
        self.create_make_order_layout()

    def hide_all(self):
        self.hide_welcome_message_layout()
        self.hide_customer_profile_layout()
        self.hide_make_order_layout()
        self.hide_order_history_layout()

    def create_menu(self):
        self.menu = QVBoxLayout(self)

        self.login_description = QLabel('Logged in as: ' + self.customer_name,
                                        self)
        font = QFont()
        font.setPixelSize(20)
        font.setBold(True)
        self.login_description.setFont(font)

        self.make_order_btn = QPushButton('Make order', self)
        self.order_history_btn = QPushButton('Order history', self)
        self.profile_btn = QPushButton('Profile', self)
        self.logout_btn = QPushButton('Logout and exit', self)

        self.make_order_btn.clicked.connect(self.make_oder_button_trigger)
        self.order_history_btn.clicked.connect(
            self.order_history_button_trigger)
        self.profile_btn.clicked.connect(self.profile_button_trigger)
        self.logout_btn.clicked.connect(self.logout_button_trigger)

        self.menu.addWidget(self.login_description)
        self.menu.addWidget(self.make_order_btn)
        self.menu.addWidget(self.order_history_btn)
        self.menu.addWidget(self.profile_btn)
        self.menu.addWidget(self.logout_btn)
        self.menu.addStretch()
        self.main_layout.addLayout(self.menu)

    def create_welcome_message_layout(self):
        self.welcome_message_layout = QVBoxLayout(self)

        self.welcome_message_font = QFont()
        self.welcome_message_font.setPixelSize(12)
        self.welcome_message_text = 'Welcome in Printer DB application.\nUse menu ' \
                                    'located on the left site of window for navigation.'
        self.welcome_message = QLabel(self.welcome_message_text)
        self.welcome_message.setFont(self.welcome_message_font)
        self.welcome_message_layout.addWidget(self.welcome_message)
        self.welcome_message_layout.addStretch()
        self.main_layout.addLayout(self.welcome_message_layout)

    def hide_welcome_message_layout(self):
        self.welcome_message.hide()

    def show_welcome_message_layout(self):
        self.welcome_message.show()

    def create_customer_profile_layout(self):
        self.customer_profile_grid = QGridLayout()
        self.customer_profile_layout = QVBoxLayout()

        self.customer_profile_info = QLabel('Profile: ', self)

        self.customer_profile_info_font = QFont()
        self.customer_profile_info_font.setPixelSize(16)
        self.customer_profile_info_font.setBold(True)
        self.customer_profile_info.setFont(self.customer_profile_info_font)

        self.customer_profile_layout.addWidget(self.customer_profile_info)

        self.password_label = QLabel('Password:'******'First name:', self)
        self.first_name_field = QLineEdit(self)

        self.last_name_label = QLabel('Last name:', self)
        self.last_name_field = QLineEdit(self)

        self.phone_label = QLabel('Phone number:', self)
        self.phone_field = QLineEdit(self)

        self.address_label = QLabel('Address:', self)
        self.address_field = QLineEdit(self)

        self.city_label = QLabel('City:', self)
        self.city_field = QLineEdit(self)

        self.loyalty_points_label = QLabel('Loyalty points:', self)
        self.loyalty_points_field = QLabel('numa', self)

        self.profile_change_button = QPushButton('Apply', self)
        self.profile_change_button.clicked.connect(
            self.apply_profile_change_button_trigger)

        self.customer_profile_grid.addWidget(self.password_label, 0, 0)
        self.customer_profile_grid.addWidget(self.password_field, 0, 1)
        self.customer_profile_grid.addWidget(self.first_name_label, 1, 0)
        self.customer_profile_grid.addWidget(self.first_name_field, 1, 1)
        self.customer_profile_grid.addWidget(self.last_name_label, 2, 0)
        self.customer_profile_grid.addWidget(self.last_name_field, 2, 1)
        self.customer_profile_grid.addWidget(self.phone_label, 3, 0)
        self.customer_profile_grid.addWidget(self.phone_field, 3, 1)
        self.customer_profile_grid.addWidget(self.address_label, 4, 0)
        self.customer_profile_grid.addWidget(self.address_field, 4, 1)
        self.customer_profile_grid.addWidget(self.city_label, 5, 0)
        self.customer_profile_grid.addWidget(self.city_field, 5, 1)
        self.customer_profile_grid.addWidget(self.first_name_label, 6, 0)
        self.customer_profile_grid.addWidget(self.first_name_field, 6, 1)
        self.customer_profile_grid.addWidget(self.loyalty_points_label, 7, 0)
        self.customer_profile_grid.addWidget(self.loyalty_points_field, 7, 1)
        self.customer_profile_grid.addWidget(self.profile_change_button, 8, 1)

        self.customer_profile_layout.addLayout(self.customer_profile_grid)
        self.customer_profile_layout.addStretch()
        self.main_layout.addLayout(self.customer_profile_layout)
        self.hide_customer_profile_layout()

    def hide_customer_profile_layout(self):
        self.customer_profile_info.hide()
        self.password_label.hide()
        self.password_field.hide()
        self.first_name_label.hide()
        self.first_name_field.hide()
        self.last_name_label.hide()
        self.last_name_field.hide()
        self.phone_label.hide()
        self.phone_field.hide()
        self.address_label.hide()
        self.address_field.hide()
        self.city_label.hide()
        self.city_field.hide()
        self.loyalty_points_label.hide()
        self.loyalty_points_field.hide()
        self.profile_change_button.hide()

    def show_customer_profile_layout(self):

        self.update_customer_profile_layout()

        self.customer_profile_info.show()
        self.password_label.show()
        self.password_field.show()
        self.first_name_label.show()
        self.first_name_field.show()
        self.last_name_label.show()
        self.last_name_field.show()
        self.phone_label.show()
        self.phone_field.show()
        self.address_label.show()
        self.address_field.show()
        self.city_label.show()
        self.city_field.show()
        self.loyalty_points_label.show()
        self.loyalty_points_field.show()
        self.profile_change_button.show()

    def update_customer_profile_layout(self):
        SQL_command = "SELECT * FROM customer WHERE username = '******'"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)

        res = cursor.fetchone()
        self.first_name_field.setText(res.first_name)
        self.last_name_field.setText(res.last_name)
        self.phone_field.setText(res.phone)
        self.address_field.setText(res.address)
        self.city_field.setText(res.city)
        self.loyalty_points_field.setText(str(res.loyalty_points))

    def create_make_order_layout(self):

        self.make_order_layout = QVBoxLayout(self)
        self.make_order_grid = QGridLayout()

        self.make_order_info = QLabel('Make an order: ', self)
        self.make_order_info_font = QFont()
        self.make_order_info_font.setPixelSize(16)
        self.make_order_info_font.setBold(True)

        self.make_order_info.setFont(self.customer_profile_info_font)
        self.make_order_layout.addWidget(self.make_order_info)

        self.due_date_label = QLabel('Due date:', self)
        self.due_date_field = QDateEdit(self)

        self.filename_label = QLabel('File: ', self)
        self.filename_field = QLineEdit(self)

        self.filament_type_label = QLabel('Filament type:', self)
        self.filament_type_field = QListWidget(self)
        self.filament_type_field.addItem('ABS')
        self.filament_type_field.addItem('PLA')

        self.filament_color_label = QLabel('Filament color:', self)
        self.filament_color_field = QListWidget(self)
        self.filament_color_field.addItem('red')
        self.filament_color_field.addItem('green')
        self.filament_color_field.addItem('blue')
        self.filament_color_field.addItem('black')
        self.filament_color_field.addItem('white')
        self.filament_color_field.addItem('yellow')
        self.filament_color_field.addItem('pink')

        self.make_order_apply_button = QPushButton('Make order', self)
        self.make_order_apply_button.clicked.connect(
            self.apply_make_order_button_trigger)

        self.make_order_grid.addWidget(self.due_date_label, 0, 0)
        self.make_order_grid.addWidget(self.due_date_field, 0, 1)
        self.make_order_grid.addWidget(self.filename_label, 1, 0)
        self.make_order_grid.addWidget(self.filename_field, 1, 1)
        self.make_order_grid.addWidget(self.filament_type_label, 2, 0)
        self.make_order_grid.addWidget(self.filament_type_field, 2, 1)
        self.make_order_grid.addWidget(self.filament_color_label, 3, 0)
        self.make_order_grid.addWidget(self.filament_color_field, 3, 1)
        self.make_order_grid.addWidget(self.make_order_apply_button, 4, 1)

        self.make_order_layout.addLayout(self.make_order_grid)
        self.make_order_layout.addStretch()
        self.main_layout.addLayout(self.make_order_layout)
        self.hide_make_order_layout()

    def hide_make_order_layout(self):
        self.make_order_info.hide()
        self.due_date_label.hide()
        self.due_date_field.hide()
        self.filename_label.hide()
        self.filename_field.hide()
        self.filament_type_label.hide()
        self.filament_type_field.hide()
        self.filament_color_label.hide()
        self.filament_color_field.hide()
        self.make_order_apply_button.hide()

    def show_make_order_layout(self):
        self.make_order_info.show()
        self.due_date_label.show()
        self.due_date_field.show()
        self.filename_label.show()
        self.filename_field.show()
        self.filament_type_label.show()
        self.filament_type_field.show()
        self.filament_color_label.show()
        self.filament_color_field.show()
        self.make_order_apply_button.show()

    def create_order_history_layout(self):
        self.order_history_layout = QVBoxLayout(self)
        self.order_history_info = QLabel('Order history: ', self)
        self.order_history_info_font = QFont()
        self.order_history_info_font.setPixelSize(16)
        self.order_history_info_font.setBold(True)

        self.order_history_info.setFont(self.customer_profile_info_font)
        self.order_history_layout.addWidget(self.order_history_info)

        self.order_history_table = QTableWidget(self)
        self.order_history_layout.addWidget(self.order_history_table)
        self.main_layout.addLayout(self.order_history_layout)
        self.order_history_table.setColumnCount(5)
        self.order_history_table.setHorizontalHeaderLabels([
            'Filename', 'Filament type', 'Filament color', 'Due date',
            'Completed', 'Cost'
        ])
        self.hide_order_history_layout()

    def hide_order_history_layout(self):
        self.order_history_info.hide()
        self.order_history_table.hide()

    def show_order_history_layout(self):
        self.update_order_history_layout()
        self.order_history_info.show()
        self.order_history_table.show()

    def update_order_history_layout(self):
        SQL_command = "SELECT stl_filename, filament_type, filament_color, due_date, completion_date, cost \
        FROM customer JOIN print_3d ON customer.username = print_3d.customer_username \
        WHERE customer.username = '******'"
        SQL_command += "ORDER BY due_date"
        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        res = cursor.fetchone()
        self.order_history = []

        while res is not None:
            self.order_history.append(res)
            res = cursor.fetchone()
        self.order_history_table.setRowCount(len(self.order_history))
        for i in range(0, len(self.order_history)):
            self.order_history_table.setItem(
                i, 0, QTableWidgetItem(self.order_history[i].stl_filename))
            self.order_history_table.setItem(
                i, 1, QTableWidgetItem(self.order_history[i].filament_type))
            self.order_history_table.setItem(
                i, 2, QTableWidgetItem(self.order_history[i].filament_color))
            self.order_history_table.setItem(
                i, 3,
                QTableWidgetItem(str(self.order_history[i].due_date)[0:10]))

            if self.order_history[i].completion_date is not None:
                completion = 'Yes'
            else:
                completion = 'Not'
            self.order_history_table.setItem(i, 4,
                                             QTableWidgetItem(completion))
            self.order_history_table.setItem(
                i, 5, QTableWidgetItem(str(self.order_history[i].cost)))

    def order_history_button_trigger(self):
        self.hide_all()
        self.show_order_history_layout()

    def make_oder_button_trigger(self):
        self.hide_all()
        self.show_make_order_layout()

    def apply_make_order_button_trigger(self):
        due_date = self.due_date_field.date()
        due_date = due_date.toPyDate()
        filename = self.filename_field.text()

        print_time = str(randint(0, 15)) + ':' + str(randint(0, 59))
        print_cost = str(randint(0, 50))

        if len(filename) == 0:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Please insert model filename")
            popup.setWindowTitle("Error - no modelname")
            popup.exec_()
            return

        if self.filament_type_field.currentItem() is None:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Please select filament type")
            popup.setWindowTitle("Error - no filament type")
            popup.exec_()
            return
        filament_type = self.filament_type_field.currentItem().text()
        if self.filament_color_field.currentItem() is None:
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Critical)
            popup.setText("Please select filament color")
            popup.setWindowTitle("Error - no filament color")
            popup.exec_()
            return
        filament_color = self.filament_color_field.currentItem().text()
        SQL_command = "INSERT INTO print_3d (printer_id, customer_username, due_date, completion_date," \
                      " estimated_printing_time, stl_filename, cost, filament_type, filament_color) " \
                      "VALUES(NULL, '"
        SQL_command += self.customer_name + "', '"
        SQL_command += str(due_date) + "', NULL, '"
        SQL_command += print_time + "', '"
        SQL_command += filename + "', "
        SQL_command += print_cost + ", '"
        SQL_command += filament_type + "', '"
        SQL_command += filament_color + "');"

        cursor = self.db_connection.cursor()
        cursor.execute(SQL_command)
        self.db_connection.commit()
        popup = QMessageBox()
        popup.setIcon(QMessageBox.Information)
        popup.setText("Successfully made an order")
        popup.setWindowTitle("Order sent")
        popup.exec_()

    def profile_button_trigger(self):
        self.hide_all()
        self.show_customer_profile_layout()

    def apply_profile_change_button_trigger(self):
        change = False

        SQL_command = 'UPDATE customer SET '

        if len(self.password_field.text()) != 0:
            password = self.password_field.text()
            m = hashlib.sha512()
            m.update(password.encode())
            password_hash = m.hexdigest()
            SQL_command += "password_hash = '"
            SQL_command += password_hash + "', "

        if len(self.first_name_field.text()) != 0:
            SQL_command += "first_name = '"
            SQL_command += self.first_name_field.text() + "', "

            change = True

        if len(self.last_name_field.text()) != 0:
            SQL_command += "last_name = '"
            SQL_command += self.last_name_field.text() + "', "
            change = True

        if len(self.phone_field.text()) == 9:
            SQL_command += "phone = '"
            SQL_command += self.phone_field.text() + "', "
            change = True

        if len(self.address_field.text()) != 0:
            SQL_command += "address = '"
            SQL_command += self.address_field.text() + "', "
            change = True

        if len(self.city_field.text()) != 0:
            SQL_command += "city = '"
            SQL_command += self.city_field.text() + "', "
            change = True

        SQL_command = SQL_command[:-2]

        SQL_command += 'WHERE username = '******'" + self.customer_name + "'"

        if change == True:
            cursor = self.db_connection.cursor()
            cursor.execute(SQL_command)
            self.db_connection.commit()
            popup = QMessageBox()
            popup.setIcon(QMessageBox.Information)
            popup.setText("Successfully applied changes to profile")
            popup.setWindowTitle("Profile Updated")
            popup.exec_()

    def logout_button_trigger(self):
        self.destroy()
        exit(0)
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 textbox - pythonspot.com'
        self.left = 20
        self.top = 40
        self.width = 4000
        self.height = 3400
        self.initUI()
        data1r = 0
        data2r = 0

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create textbox

        self.label = QLabel('Nome Azione', self)
        self.label.move(100, 160)
        self.label.show()

        self.nome = QLineEdit(self)
        self.nome.move(300, 160)
        self.nome.show()

        self.dat1 = QDateEdit(self)
        self.dat1.move(500, 160)
        self.dat1.show()

        self.dat2 = QDateEdit(self)
        self.dat2.move(800, 160)
        self.dat2.show()

        # Create a button in the window
        self.button = QPushButton('Show text', self)
        self.button.move(400, 260)

        # connect button to function on_click
        self.button.clicked.connect(self.on_click)
        self.show()

    @pyqtSlot()
    def on_click(self):
        textboxValue = self.nome.text()
        data1g = self.dat1.text()
        data1r = datetime.datetime.strptime(data1g,
                                            "%d/%m/%Y").strftime("%Y-%m-%d")

        data2g = self.dat2.text()
        data2r = datetime.datetime.strptime(data2g,
                                            "%d/%m/%Y").strftime("%Y-%m-%d")

        print(data1r)
        print(data2r)

        if (textboxValue == ""):

            QMessageBox.question(self, 'Message - pythonspot.com',
                                 "You typed  Blank: " + textboxValue,
                                 QMessageBox.Ok, QMessageBox.Ok)
            self.textbox.setText("")
        else:
            QMessageBox.question(self, 'Message - pythonspot.com',
                                 "You typed: " + textboxValue, QMessageBox.Ok,
                                 QMessageBox.Ok)
            grafica(textboxValue, data1r, data2r)
class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'grafiko_kreator'
        self.left = 20
        self.top = 50
        self.width = 2600
        self.height = 1000
        self.number_of_hours = 0
        self.number_of_days = QDate.daysInMonth(QDate.currentDate())
        self.workers_number = 3
        self.slaveowners_number = 3
        self.date_box = QDateEdit()
        self.date = QDate.currentDate()
        self.initUI()


    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createTable()
        self.askfordate()
        self.number_of_wokers()
        self.number_of_slaveowners()
        self.update_table_button()
        self.workers_label()
        self.slaveowners_label()
        # Add box layout, add table to box layout and add box layout to widget
        self.Vlayout = QVBoxLayout()
        self.Hlayout = QHBoxLayout()

        self.Vlayout.addWidget(self.tableWidget)
        self.Vlayout.addLayout(self.Hlayout)
        self.Hlayout.addWidget(self.workers_box)
        self.Hlayout.addWidget(self.w_label)
        self.Hlayout.addWidget(self.slaveowners_box)
        self.Hlayout.addWidget(self.s_label)
        self.Hlayout.addWidget(self.update_button)
        self.Hlayout.addWidget(self.update_button)
        self.Vlayout.addWidget(self.date_box)
        self.setLayout(self.Vlayout)

        # Show widget
        self.show()

    def createTable(self):
        # Create table
        number_of_rows = self.slaveowners_number + self.workers_number+1
        number_of_columns = self.number_of_days+2
        date = self.date
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(number_of_rows)
        self.tableWidget.setColumnCount(number_of_columns)
        horizontal_labels = []
        vertical_labels = []
        horizontal_labels.append('Pracownik/dzień')
        vertical_labels.append('')
        sunday_dates = []
        current_day_number = 0
        for i in range (number_of_columns-2):
            horizontal_labels.append(str(i+1))
        for i in range (number_of_columns):
            vertical_labels.append(str(i+1))
        horizontal_labels.append('suma')
        self.tableWidget.setHorizontalHeaderLabels(horizontal_labels)
        self.tableWidget.setVerticalHeaderLabels(vertical_labels)
        for i in range (number_of_rows):
            self.tableWidget.setRowHeight(i,20)
        for i in range (number_of_columns):
            self.tableWidget.setColumnWidth(i,80)
        self.tableWidget.move(0, 0)

        # table selection change
        for i in range(1,self.number_of_days+1):
            date.setDate(date.year(),date.month(),i)
            self.tableWidget.setItem(0,i,QTableWidgetItem(QDate.shortDayName(date.dayOfWeek())))
            #print(QDate.longDayName(date.dayOfWeek()))
        self.tableWidget.doubleClicked.connect(self.on_click)
        self.tableWidget.resizeColumnToContents(0)
        self.tableWidget.resizeRowsToContents()
        self.tableWidget.selectRow(0)
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            current_day_number +=1
            if currentQTableWidgetItem.text() == 'niedz.':
                sunday_dates.append(current_day_number)
        for j in range (len(sunday_dates)-1):
            for i in range (number_of_rows):
                self.tableWidget.setItem(i+1,sunday_dates[j],QTableWidgetItem("x"))

        self.tableWidget.itemChanged.connect(self.isLast)
        self.how_many_hours()
        self.give_full_hours()
        self.show()

    def number_of_wokers(self):
        self.workers_box = QLineEdit()
        self.workers_box.setMaximumWidth(200)


    def number_of_slaveowners(self):
        self.slaveowners_box = QLineEdit()
        self.slaveowners_box.setMaximumWidth(200)

    def update_table_button(self):
        self.update_button = QPushButton('update')
        self.update_button.setMaximumWidth(200)
        self.update_button.clicked.connect(self.update_rows)

    def workers_label(self):
        self.w_label = QLabel('Ile pracowników')

    def slaveowners_label(self):
        self.s_label = QLabel('ile prowadzących zmiany')

    def askfordate(self):
        self.date_box.setDate(QDate.currentDate())
        self.date_box.setMaximumSize(200,50)
        self.date_box.move(0,300)
        self.date_box.show()
        self.date_box.setCalendarPopup(True)
        self.date_box.dateChanged.connect(self.update_date)
        #self.date_box.dateChanged.connect(self.createTable)

    def how_many_hours(self):
        hours_count = 0
        working_date = self.date
        for i in range (working_date.daysInMonth()):
            working_date.setDate(working_date.year(), working_date.month(), i+1)
            if working_date.dayOfWeek()>0 and working_date.dayOfWeek()<6:
                hours_count+=8
        print(hours_count)
        self.number_of_hours = hours_count

    def give_free_days(self):
        propability_table = []
        for i in range(self.number_of_days):
            for j in range(self.slaveowners_number+self.workers_number):
                try:
                    if self.tableWidget.item(i,j).text()=='x':
                        propability_table.append(1)
                except:
                    pass
        


    def give_full_hours(self):
        for i in range(self.workers_number+self.slaveowners_number):
            hours_for_person = self.number_of_hours
            number_of_free_days = self.number_of_days-int(round(hours_for_person/11.5,0))
            assigned_free_days = 0
            j=0
            # for j in range(self.number_of_days):
            while hours_for_person > 0 and assigned_free_days<number_of_free_days:
                two_free = False
                two_work = False
                try:
                    two_free = (self.tableWidget.item(i + 1, j - 1).text() == self.tableWidget.item(i + 1, j).text()=='x')
                    two_work = (self.tableWidget.item(i + 1, j - 1).text() == self.tableWidget.item(i + 1, j).text()=='11.5')
                except:
                    pass
                try:

                    if (self.tableWidget.item(i+1,j+1).text())=='x' and assigned_free_days-number_of_free_days!=0:
                        assigned_free_days+=1
                        j+=1
                    else:
                        j+=1
                except:
                    is_ramdomly_free = random.random() < (number_of_free_days-assigned_free_days)/((self.number_of_days-j)+np.power(10.0,-100))
                    if is_ramdomly_free and assigned_free_days-number_of_free_days!=0 and not two_free or two_work:
                        self.tableWidget.setItem(i+1,j+1,QTableWidgetItem(str('x')))
                        j+=1
                        assigned_free_days+=1
                    elif self.is_enough_today(j+1) and assigned_free_days-number_of_free_days!=0 and not two_free or two_work:
                        self.tableWidget.setItem(i + 1, j + 1, QTableWidgetItem(str('x')))
                        j+=1
                        assigned_free_days+=1
                    elif not self.is_enough_today(j+1):
                        self.tableWidget.setItem(i+1,j+1,QTableWidgetItem(str(11.5)))
                        hours_for_person-=11.5
                        j+=1
                    else:
                        self.tableWidget.setItem(i + 1, j + 1, QTableWidgetItem(str('x')))
                        j += 1
                        assigned_free_days += 1
            self.tableWidget.setItem(i+1,j,QTableWidgetItem(str(hours_for_person)))
        self.isLast()

    def is_enough_today(self,day):
        number_of_todays_workers = 0
        for i in range (self.slaveowners_number+self.workers_number):
            try:
                if self.tableWidget.item(i,day).text()=='11.5':
                    number_of_todays_workers+=1
            except:
                pass
        return number_of_todays_workers > 2

    @pyqtSlot()
    def isLast(self):
        try:
            column = self.tableWidget.currentItem().column()
            if column == self.number_of_days+1:
                pass
            else:
                self.count()
        except:
            pass
    def on_click(self):
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

    def update_rows(self):
        self.slaveowners_number = int(self.slaveowners_box.text())
        self.workers_number = int(self.workers_box.text())
        rows = self.slaveowners_number+self.workers_number
        difference = self.tableWidget.rowCount()-(rows+2)
        for i in range(abs(difference+1)):
            if (difference<0):
                self.tableWidget.insertRow(i+1)
            if (difference>0):
                self.tableWidget.removeRow(self.tableWidget.rowCount()-1)
        vertical_labels = []
        vertical_labels.append('')
        for i in range(rows):
            vertical_labels.append(str(i + 1))

        self.tableWidget.setVerticalHeaderLabels(vertical_labels)
        self.tableWidget.resizeRowsToContents()

    def count(self):
        suma = 0

        row = self.tableWidget.currentItem().row()
        #print(type(int(self.tableWidget.currentItem().text())))
        for i in range(self.number_of_days+1):
            try:
                 suma+=float(self.tableWidget.item(row,i).text())

            except:
                pass
        try:
            self.tableWidget.selectColumn(self.number_of_days+1)
            self.tableWidget.setItem(row,self.number_of_days+1,QTableWidgetItem(str(suma)))
        except:
            pass
        # self.tableWidget.setItem(row,self.number_of_days,QTableWidgetItem(suma))

    def update_date(self):
        current_day_number = 0
        sunday_dates = []
        days = QDate.daysInMonth(self.date_box.date())
        columns = days+1
        number_of_rows = self.workers_number+self.slaveowners_number
        self.date=self.date_box.date()
        date = self.date
        difference = self.number_of_days-(days)
        for i in range(abs(difference)):
            if (difference<0):
                print(difference)
                self.tableWidget.insertColumn(i)
            if (difference>0):
                print(difference)
                self.tableWidget.removeColumn(days-i)
        self.number_of_days = days
        self.tableWidget.clear()

        horizontal_labels = []
        horizontal_labels.append('Pracownik/dzień')
        for i in range(days):
            horizontal_labels.append(str(i + 1))
        horizontal_labels.append('suma')
        self.tableWidget.setHorizontalHeaderLabels(horizontal_labels)
        for i in range(self.tableWidget.rowCount()):
            self.tableWidget.setRowHeight(i, 20)
        for i in range(days+1):
            self.tableWidget.setColumnWidth(i, 80)
        for i in range(1, days+1):
           date.setDate(date.year(), date.month(), i)
           self.tableWidget.setItem(0, i, QTableWidgetItem(QDate.shortDayName(date.dayOfWeek())))

        self.tableWidget.selectRow(0)
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            current_day_number += 1
            if currentQTableWidgetItem.text() == 'niedz.':
                sunday_dates.append(current_day_number)
        for j in range(len(sunday_dates) - 1):
            for i in range(number_of_rows):
                self.tableWidget.setItem(i + 1, sunday_dates[j], QTableWidgetItem("x"))
        self.tableWidget.resizeColumnToContents(0)
        self.tableWidget.resizeRowsToContents()
        self.how_many_hours()
        self.show()
Exemple #4
0
class Table(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'grafiko_kreator'
        self.left = 20
        self.top = 50
        self.width = 2600
        self.height = 1000
        self.number_of_hours = 0
        self.number_of_days = QDate.daysInMonth(QDate.currentDate())
        self.workers_number = 3
        self.slaveowners_number = 3
        self.sunday_dates = []
        self.date_box = QDateEdit()
        self.date = QDate.currentDate()
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createTable()
        self.askfordate()
        self.number_of_wokers()
        self.number_of_slaveowners()
        self.update_table_button()
        self.workers_label()
        self.slaveowners_label()
        # Add box layout, add table to box layout and add box layout to widget
        self.Vlayout = QVBoxLayout()
        self.Hlayout = QHBoxLayout()

        self.Vlayout.addWidget(self.tableWidget)
        self.Vlayout.addLayout(self.Hlayout)
        self.Hlayout.addWidget(self.workers_box)
        self.Hlayout.addWidget(self.w_label)
        self.Hlayout.addWidget(self.slaveowners_box)
        self.Hlayout.addWidget(self.s_label)
        self.Hlayout.addWidget(self.update_button)
        self.Hlayout.addWidget(self.update_button)
        self.Vlayout.addWidget(self.date_box)
        self.setLayout(self.Vlayout)
        self.tableWidget.itemChanged.connect(self.isLast)
        # Show widget
        self.show()

    def createTable(self):
        # Create table
        number_of_rows = self.slaveowners_number + self.workers_number + 1
        number_of_columns = self.number_of_days + 2
        date = self.date
        self.tableWidget = QTableWidget()
        self.tableWidget.setRowCount(number_of_rows)
        self.tableWidget.setColumnCount(number_of_columns)
        horizontal_labels = []
        vertical_labels = []
        horizontal_labels.append('Pracownik/dzień')
        vertical_labels.append('')

        for i in range(number_of_columns - 2):
            horizontal_labels.append(str(i + 1))
        for i in range(number_of_columns):
            vertical_labels.append(str(i + 1))
        horizontal_labels.append('suma')
        self.tableWidget.setHorizontalHeaderLabels(horizontal_labels)
        self.tableWidget.setVerticalHeaderLabels(vertical_labels)
        for i in range(number_of_rows):
            self.tableWidget.setRowHeight(i, 20)
        for i in range(number_of_columns):
            self.tableWidget.setColumnWidth(i, 80)
        self.tableWidget.move(0, 0)

        # table selection change
        for i in range(1, self.number_of_days + 1):
            date.setDate(date.year(), date.month(), i)
            self.tableWidget.setItem(
                0, i, QTableWidgetItem(QDate.shortDayName(date.dayOfWeek())))
            # print(QDate.longDayName(date.dayOfWeek()))
        self.tableWidget.resizeColumnToContents(0)
        self.tableWidget.resizeRowsToContents()
        self.sundays()
        self.how_many_hours()
        self.count()

        self.show()

    def sundays(self):
        number_of_rows = self.slaveowners_number + self.workers_number + 1
        self.sunday_dates = []
        current_day_number = 0
        self.tableWidget.selectRow(0)
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            current_day_number += 1
            if currentQTableWidgetItem.text() == 'niedz.':
                self.sunday_dates.append(current_day_number)
        for j in range(len(self.sunday_dates) - 1):
            for i in range(number_of_rows):
                self.tableWidget.setItem(i + 1, self.sunday_dates[j],
                                         QTableWidgetItem("x"))

    def change_item(self, row, column, value):
        if value != 'y':
            self.tableWidget.setItem(row, column, QTableWidgetItem(str(value)))
        elif value == 'y':
            self.tableWidget.setItem(row, column, QTableWidgetItem(str(11.5)))
            self.tableWidget.item(row, column).setBackground(
                QtGui.QColor(255, 0, 0))

    def number_of_wokers(self):
        self.workers_box = QLineEdit()
        self.workers_box.setMaximumWidth(200)

    def number_of_slaveowners(self):
        self.slaveowners_box = QLineEdit()
        self.slaveowners_box.setMaximumWidth(200)

    def update_table_button(self):
        self.update_button = QPushButton('update')
        self.update_button.setMaximumWidth(200)

    def workers_label(self):
        self.w_label = QLabel('Ile pracowników')

    def slaveowners_label(self):
        self.s_label = QLabel('ile prowadzących zmiany')

    def askfordate(self):
        self.date_box.setDate(QDate.currentDate())
        self.date_box.setMaximumSize(200, 50)
        self.date_box.move(0, 300)
        self.date_box.show()
        self.date_box.setCalendarPopup(True)
        # self.date_box.dateChanged.connect(self.createTable)

    def how_many_hours(self):
        hours_count = 0
        working_date = self.date
        for i in range(working_date.daysInMonth()):
            working_date.setDate(working_date.year(), working_date.month(),
                                 i + 1)
            if working_date.dayOfWeek() > 0 and working_date.dayOfWeek() < 6:
                hours_count += 8
        self.number_of_hours = hours_count

    @pyqtSlot()
    def isLast(self):
        try:
            self.tableWidget.currentItem().setBackground(
                QtGui.QColor(255, 255, 255))
            column = self.tableWidget.currentItem().column()
            if column == self.number_of_days + 1:
                pass
            else:
                self.count()
        except:
            column = self.tableWidget.currentColumn()
            pass

    def count(self):
        for row in range(self.slaveowners_number + self.workers_number):
            suma = 0
            for column in range(self.number_of_days):
                try:
                    suma += float(
                        self.tableWidget.item(row + 1, column + 1).text())
                except:
                    pass
            self.tableWidget.selectColumn(column + 2)
            self.tableWidget.setItem(row + 1, column + 2,
                                     QTableWidgetItem(str(suma)))


#
# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     ex = Table()
#     sys.exit(app.exec_())
Exemple #5
0
class StatsWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.date = datetime.today()
        self.date = self.date.strftime('%Y-%m-%d')

        self.l1 = QLabel('Please choose the period of time for which to diplay the data: ')
        self.buttonDaily = QPushButton('daily')
        self.buttonMonthly = QPushButton('monthly')
        self.buttonPeriod = QPushButton('set period')

        self.buttonDaily.clicked.connect(self.daily)
        self.buttonMonthly.clicked.connect(self.monthly)
        self.buttonPeriod.clicked.connect(self.period)

        sublayoutTime = QHBoxLayout()
        sublayoutTime.addWidget(self.l1)
        sublayoutTime.addWidget(self.buttonDaily)
        sublayoutTime.addWidget(self.buttonMonthly)
        sublayoutTime.addWidget(self.buttonPeriod)
        sublayoutTime.setAlignment(Qt.AlignRight);

        self.l2 = QLabel('Select the date: ')
        self.l3 = QLabel('   Select the end date: ')

        self.dateedit = QDateEdit(calendarPopup=True)
        self.dateedit.setDateTime(QDateTime.currentDateTime())
        self.startDate = QDateEdit(calendarPopup=True)
        self.startDate.setDateTime(QDateTime.currentDateTime())
        self.endDate = QDateEdit(calendarPopup=True)
        self.endDate.setDateTime(QDateTime.currentDateTime())

        self.l3.hide()
        self.startDate.hide()
        self.endDate.hide()

        self.monthList = QDateEdit()
        self.monthList.setDisplayFormat("MMM")
        self.monthList.setDateTime(QDateTime.currentDateTime())
        self.monthList.hide()

        self.yearList = QDateEdit()
        self.yearList.setDisplayFormat("yyyy")
        self.yearList.setDateTime(QDateTime.currentDateTime())
        self.yearList.hide()

        self.l4 = QLabel("'Start date' should be before 'end date'!")
        self.l4.setStyleSheet("QWidget {color : rgba(255,0,0,255);}")
        self.l4.hide()

        sublayoutSelectDate = QHBoxLayout()
        sublayoutSelectDate.addWidget(self.l2)
        sublayoutSelectDate.addWidget(self.dateedit)
        sublayoutSelectDate.addWidget(self.monthList)
        sublayoutSelectDate.addWidget(self.yearList)
        sublayoutSelectDate.addWidget(self.startDate)
        sublayoutSelectDate.addWidget(self.l3)
        sublayoutSelectDate.addWidget(self.endDate)
        sublayoutSelectDate.setAlignment(Qt.AlignRight);

        self.button_show_layout = QHBoxLayout()
        self.buttonShow = QPushButton('Show Analytics')
        self.buttonShow.clicked.connect(self.update)
        self.button_show_layout.addWidget(QLabel())
        self.button_show_layout.addWidget(QLabel())
        self.button_show_layout.addWidget(self.buttonShow)

        sublayoutTimeSelect = QVBoxLayout()
        sublayoutTimeSelect.addLayout(sublayoutTime)
        sublayoutTimeSelect.addLayout(sublayoutSelectDate)
        sublayoutTimeSelect.addWidget(self.l4, alignment=Qt.AlignRight)
        sublayoutTimeSelect.addLayout(self.button_show_layout)

        self.button1 = QPushButton('Hourly Call Summary')
        self.button2 = QPushButton('Initial Calling Outcome')
        self.button3 = QPushButton('Redirected Calls')
        self.button4 = QPushButton('IVR Call Drop Rate')

        self.outcomes, self.time, self.redirect = return_daily_data(self.date)
        self.graph = 1
        self.period = 'daily'
        self.day = datetime.today().strftime('%d %B %Y')
        self.month = datetime.today().strftime('%B')
        self.year = datetime.today().strftime('%Y')
        self.fromDate = datetime.today().strftime('%d %B %Y')
        self.toDate = datetime.today().strftime('%d %B %Y')
        self.plot1()

        self.button1.clicked.connect(self.plot1)
        self.button2.clicked.connect(self.plot2)
        self.button3.clicked.connect(self.plot3)
        self.button4.clicked.connect(self.plot4)

        sublayout1 = QHBoxLayout()
        sublayout1.addWidget(self.button1)
        sublayout1.addWidget(self.button2)

        sublayout2 = QHBoxLayout()
        sublayout2.addWidget(self.button3)
        sublayout2.addWidget(self.button4)

        sublayout = QVBoxLayout()
        sublayout.addLayout(sublayout1)
        sublayout.addLayout(sublayout2)

        back_button_creator = BackButton()
        self.back_button = back_button_creator.create_back_button()
        back_layout = back_button_creator.create_back_layout(self.back_button)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.toolbar)
        main_layout.addLayout(sublayoutTimeSelect)
        main_layout.addWidget(self.canvas)
        main_layout.addLayout(sublayout)
        main_layout.addLayout(back_layout)

        self.setLayout(main_layout)

    def update(self):
        self.l4.hide()
        if self.period == 'daily':
            date = self.dateedit.date().toPyDate().strftime('%Y-%m-%d')
            self.outcomes, self.time, self.redirect = return_daily_data(date)
            self.day = self.dateedit.date().toPyDate().strftime('%d %B %Y')
            print(self.day)
        elif self.period == 'monthly':
            month = self.monthList.date().toPyDate().strftime('%m')
            year = self.yearList.date().toPyDate().strftime('%Y')
            self.outcomes, self.time, self.redirect = return_monthly_data(year + '-' + month)
            self.month = self.monthList.date().toPyDate().strftime('%B')
            self.year = self.yearList.date().toPyDate().strftime('%Y')
        elif self.period == 'period':
            start = self.startDate.date().toPyDate()
            end = self.endDate.date().toPyDate()
            if start > end:
                self.l4.show()
            else:
                self.outcomes, self.time, self.redirect = return_period_data(start, end)
            self.fromDate = self.startDate.date().toPyDate().strftime('%d %B %Y')
            self.toDate = self.endDate.date().toPyDate().strftime('%d %B %Y')
        if self.graph == 1:
            self.plot1()
        elif self.graph == 2:
            self.plot2()
        elif self.graph == 3:
            self.plot3()
        else:
            self.plot4()

    def daily(self):
        self.period = 'daily'
        self.dateedit.show()
        self.monthList.hide()
        self.l2.setText('Select the date: ')
        self.l3.hide()
        self.startDate.hide()
        self.endDate.hide()
        self.update()
        self.monthList.hide()
        self.yearList.hide()

    def monthly(self):
        self.period = 'monthly'
        self.dateedit.hide()
        self.monthList.show();
        self.l2.setText('Select the month: ')
        self.l3.hide()
        self.startDate.hide()
        self.endDate.hide()
        self.update()
        self.monthList.show()
        self.yearList.show()

    def period(self):
        self.period = 'period'
        self.dateedit.hide()
        self.monthList.hide()
        self.l2.setText('Select the start date: ')
        self.l3.show()
        self.startDate.show()
        self.endDate.show()
        self.update()
        self.monthList.hide()
        self.yearList.hide()

    def plot1(self):

        COLOR = 'dimgrey'
        matplotlib.rcParams['text.color'] = COLOR
        matplotlib.rcParams['axes.labelcolor'] = COLOR
        matplotlib.rcParams['xtick.color'] = COLOR
        matplotlib.rcParams['ytick.color'] = COLOR
        matplotlib.rcParams['lines.color'] = COLOR

        self.graph = 1
        self.figure.clear()

        ax = self.figure.add_subplot()

        hours = ['Before 08:00', '08:00 - 10:00', '10:00 - 12:00', '12:00 - 14:00', '14:00 - 16:00',
                 '16:00 - 18:00', 'After 18:00']

        plt.plot(hours, self.time, marker='o')

        if self.period == 'daily':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                plt.title('There were no incoming calls on  ' + self.day, color='black')
            else:
                plt.title('Hourly call summary on  ' + self.day, color='black')
        elif self.period == 'monthly':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                plt.title('There were no incoming calls on  ' + self.month + ' ' + self.year, color='black')
            else:
                plt.title('Hourly call summary on  ' + self.month + ' ' + self.year, color='black')
        else:
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                plt.title('There were no incoming calls from  ' + self.fromDate + '  to  ' + self.toDate,
                          color='black')
            else:
                plt.title('Hourly call summary from  ' + self.fromDate + '  to  ' + self.toDate, color='black')

        plt.ylabel('Number of calls')

        self.figure.tight_layout()
        self.figure.autofmt_xdate()

        plt.grid(linestyle='--', linewidth=0.3)

        self.canvas.draw()

    def plot2(self):

        self.graph = 2
        self.figure.clear()

        ax = self.figure.add_subplot()

        possible_outcomes = ('Answered', 'No answer', 'Busy', 'Failed')
        y_pos = np.arange(len(possible_outcomes))

        ax.barh(possible_outcomes, self.outcomes[:4])

        if self.period == 'daily':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.day, color='black')
            else:
                ax.set_title('Outcome of all incoming calls on  ' + self.day, color='black')
        elif self.period == 'monthly':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.month + ' ' + self.year, color='black')
            else:
                ax.set_title('Outcome of all incoming calls on  ' + self.month + ' ' + self.year, color='black')
        else:
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls from  ' + self.fromDate + '  to  ' + self.toDate,
                             color='black')
            else:
                ax.set_title('Outcome of all incoming calls from  ' + self.fromDate + '  to  ' + self.toDate,
                             color='black')
        ax.set_yticks(y_pos)
        ax.set_yticklabels(possible_outcomes)
        ax.invert_yaxis()
        ax.set_xlabel('Number of calls')

        self.figure.tight_layout()

        plt.grid(linestyle='--', linewidth=0.3)

        self.canvas.draw()

    def plot3(self):

        self.graph = 3
        self.figure.clear()

        ax = self.figure.add_subplot()

        keys = list(self.redirect.keys())
        values = list(self.redirect.values())

        ax.bar(keys, values, width=0.4)
        ax.set_ylabel('Number of Calls')

        if self.period == 'daily':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.day, color='black')
            else:
                ax.set_title('Redirected calls on  ' + self.day, color='black')
        elif self.period == 'monthly':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.month + ' ' + self.year, color='black')
            else:
                ax.set_title('Redirected calls on  ' + self.month + ' ' + self.year, color='black')
        else:
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls from  ' + self.fromDate + '  to  ' + self.toDate,
                             color='black')
            else:
                ax.set_title('Redirected calls from  ' + self.fromDate + '  to  ' + self.toDate, color='black')

        self.figure.tight_layout()

        plt.grid(linestyle='--', linewidth=0.3)

        self.canvas.draw()

    def plot4(self):

        self.graph = 4
        self.figure.clear()

        ax = self.figure.add_subplot()

        total_calls = self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3]
        percentages = [0, 0]
        if total_calls != 0:
            dropped_percent = self.outcomes[4] * 100 / total_calls
            percentages = [100 - dropped_percent, dropped_percent]
        labels = ['Successful IVR Calls', 'Dropped IVR Calls']
        explode = (0, 0.1)

        ax.pie(percentages, explode=explode, labels=labels, autopct='%1.1f%%', textprops={'color': "k"},
                           shadow=True, startangle=-45)
        ax.axis('equal')

        if self.period == 'daily':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.day, color='black')
            else:
                ax.set_title('Call setup success rate on  ' + self.day, color='black')
        elif self.period == 'monthly':
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls on  ' + self.month + ' ' + self.year, color='black')
            else:
                ax.set_title('IVR call drop rate on  ' + self.month + ' ' + self.year, color='black')
        else:
            if self.outcomes[0] + self.outcomes[1] + self.outcomes[2] + self.outcomes[3] == 0:
                ax.set_title('There were no incoming calls from  ' + self.fromDate + '  to  ' + self.toDate,
                             color='black')
            else:
                ax.set_title('Call setup success rate from  ' + self.fromDate + '  to  ' + self.toDate,
                             color='black')
        self.canvas.draw()