Esempio n. 1
0
class EditCardioHistoryEntry(QWidget):
    update_cardio_history_signal = pyqtSignal(bool)

    def __init__(self, cardio_history, date, activity, index):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.table_name = "Weight Loss"
        self.cardio_history = cardio_history
        self.date = date
        self.activity = activity
        self.index = index
        self.entry = self.cardio_history[self.date][self.activity][self.index]
        self.setStyleSheet("""
    QWidget{
      background-color: #322d2d;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        self.cardio_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "cardio_history"))
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowFlags(Qt.Tool)
        self.setWindowTitle("Edit Cardio History Entry")
        self.create_layout()

    def create_layout(self):
        layout = QVBoxLayout()
        form_layout = QFormLayout()
        activity_parameter_label = QLabel("Activity Parameter")
        value_label = QLabel("Value")

        time_spent_label = QLabel("Time Spent")
        self.time_spent_line_edit = QLineEdit()
        self.time_spent_line_edit.setValidator(QIntValidator())
        self.time_spent_line_edit.setText(self.entry["Time Spent"])

        distance_travelled_label = QLabel("Distance Travelled")
        self.distance_travelled_line_edit = QLineEdit()
        self.distance_travelled_line_edit.setValidator(QIntValidator())
        self.distance_travelled_line_edit.setText(
            self.entry["Distance Travelled"])

        calories_burnt_label = QLabel("Calories Burnt")
        self.calories_burnt_line_edit = QLineEdit()
        self.calories_burnt_line_edit.setValidator(QIntValidator())
        self.calories_burnt_line_edit.setText(self.entry["Calories Burnt"])

        buttons_layout = QHBoxLayout()
        save_button = QPushButton("Save")
        save_button.clicked.connect(lambda: self.save_entry())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close())
        buttons_layout.addWidget(save_button)
        buttons_layout.addWidget(cancel_button)

        form_layout.addRow(activity_parameter_label, value_label)
        form_layout.addRow(time_spent_label, self.time_spent_line_edit)
        form_layout.addRow(distance_travelled_label,
                           self.distance_travelled_line_edit)
        form_layout.addRow(calories_burnt_label, self.calories_burnt_line_edit)

        layout.addLayout(form_layout)
        layout.addLayout(buttons_layout)
        self.setLayout(layout)

    def save_entry(self):
        self.date = datetime.today().strftime("%d/%m/%Y")
        new_activity_entry = {
            "Time Spent": str(self.time_spent_line_edit.text()),
            "Distance Travelled":
            str(self.distance_travelled_line_edit.text()),
            "Calories Burnt": str(self.calories_burnt_line_edit.text())
        }

        self.cardio_history[self.date][self.activity][
            self.index] = new_activity_entry
        current_cardio_history = json.dumps(self.cardio_history)
        self.db_wrapper.update_table_column(self.table_name, "cardio_history",
                                            current_cardio_history)
        self.update_cardio_history_signal.emit(True)
        self.close()
Esempio n. 2
0
class EditRadioButton(QWidget):
    def __init__(self, parent, edit_func, parameter):
        super().__init__()
        self.edit_func = edit_func
        self.this_parent = parent
        self.parameter = parameter  # goal or gender
        self.db_wrapper = DatabaseWrapper()
        self.setStyleSheet("""QWidget{
      background-color: #232120;
      color:#c7c7c7;
      font-weight: bold;
      font-family: Montserrat;
      font-size: 16px;
      }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }""")
        dialog_layout = QVBoxLayout()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setLayout(dialog_layout)
        if self.edit_func == "gender":
            layout = self.create_radio_button_gender()
        elif self.edit_func == "goal":
            layout = self.create_radio_button_goal()
        dialog_layout.addLayout(layout)

    def create_radio_button_goal(self):
        layout = QVBoxLayout()
        label = QLabel("Goal")
        #Weight loss, Maintain weight, Weight gain
        radio_button_loss = QRadioButton("Weight Loss")
        radio_button_loss.clicked.connect(
            lambda: self.db_wrapper.update_table_column(
                "Users", "goal", "Weight Loss"))
        radio_button_maintain = QRadioButton("Weight Maintain")
        radio_button_maintain.clicked.connect(
            lambda: self.db_wrapper.update_table_column(
                "Users", "goal", "Maintain weight"))
        radio_button_gain = QRadioButton("Weight Gain")
        radio_button_gain.clicked.connect(
            lambda: self.db_wrapper.update_table_column(
                "Users", "goal", "Weight gain"))

        if self.parameter == "Weight loss":
            radio_button_loss.setChecked(True)
        elif self.parameter == "Maintain weight":
            radio_button_maintain.setChecked(True)
        else:
            radio_button_gain.setChecked(True)

        close_button = QPushButton("Close")
        close_button.clicked.connect(lambda: self.close_button())

        layout.addWidget(label)
        layout.addWidget(radio_button_loss)
        layout.addWidget(radio_button_maintain)
        layout.addWidget(radio_button_gain)
        layout.addWidget(close_button)

        return layout

    def update_goal(self, goal):
        self.db_wrapper.update_goal(goal)

    def create_radio_button_gender(self):
        layout = QVBoxLayout()
        label = QLabel("Gender")

        radio_button_male = QRadioButton("Male")
        radio_button_female = QRadioButton("Female")
        radio_button_male.clicked.connect(
            lambda: self.db_wrapper.update_table_column(
                "Users", "gender", "male"))
        radio_button_female.clicked.connect(
            lambda: self.db_wrapper.update_table_column(
                "Users", "gender", "female"))

        if self.parameter == "male":
            radio_button_male.setChecked(True)
            radio_button_female.setChecked(False)
        else:
            radio_button_female.setChecked(True)
            radio_button_male.setChecked(False)

        close_button = QPushButton("Close")
        close_button.clicked.connect(lambda: self.close_button())

        layout.addWidget(label)
        layout.addWidget(radio_button_male)
        layout.addWidget(radio_button_female)
        layout.addWidget(close_button)

        return layout

    def close_button(self):
        self.this_parent.refresh_user_data()
        self.close()
Esempio n. 3
0
class CardioHistory(QScrollArea):
    refresh_cardio_labels_signal = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Weight Loss"
        self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        self.cardio_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "cardio_history"))
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("Cardio History")

        widget = QWidget()
        self.layout = QGridLayout(widget)
        self.setWidget(widget)
        self.setWidgetResizable(True)

        self.entry_count = 0
        for date in self.cardio_history:
            for activity in self.cardio_history[date]:
                self.entry_count += len(self.cardio_history[date][activity])
        self.create_history(True, True)

    @pyqtSlot(bool)
    def create_history(self, create, init_layout=False):
        if create:
            if not init_layout:
                self.refresh_cardio_labels_signal.emit(True)
                self.delete_history()

            date_label = QLabel("Date")
            date_label.setAlignment(Qt.AlignCenter)
            activity_label = QLabel("Activity")
            activity_label.setAlignment(Qt.AlignCenter)

            edit_label = QLabel("Edit")
            edit_label.setAlignment(Qt.AlignCenter)
            delete_label = QLabel("Delete")
            delete_label.setAlignment(Qt.AlignCenter)

            helper_layout = QGridLayout()

            helper_layout.addWidget(date_label, 0, 0)
            helper_layout.addWidget(activity_label, 0, 1)
            helper_layout.addWidget(edit_label, 0, 2)
            helper_layout.addWidget(delete_label, 0, 3)

            self.date_labels = [None] * self.entry_count
            self.cardio_labels = [None] * self.entry_count
            self.edit_buttons = [None] * self.entry_count
            self.delete_buttons = [None] * self.entry_count

            for i in range(self.entry_count):
                self.date_labels[i] = QLabel(self)
                self.cardio_labels[i] = QLabel(self)
                self.edit_buttons[i] = QPushButton("Edit", self)
                self.delete_buttons[i] = QPushButton("X", self)

            row = 1
            j = 0
            for date in reversed(list(self.cardio_history.keys())):
                for activity in self.cardio_history[date]:
                    if len(self.cardio_history[date][activity]) > 0:
                        for data_index, activity_data in enumerate(
                                list(
                                    reversed(
                                        self.cardio_history[date][activity]))):
                            self.cardio_labels[j].setText(activity)
                            self.date_labels[j].setText(date)
                            self.edit_buttons[j].setProperty(
                                "data_index", data_index)
                            self.edit_buttons[j].clicked.connect(
                                partial(
                                    self.edit_cardio_dialog, date, activity,
                                    self.edit_buttons[j].property(
                                        "data_index")))
                            self.delete_buttons[j].setProperty(
                                "data_index", data_index)
                            self.delete_buttons[j].clicked.connect(
                                partial(
                                    self.delete_entry, j, date, activity,
                                    self.edit_buttons[j].property(
                                        "data_index")))

                            helper_layout.addWidget(self.date_labels[j], row,
                                                    0, 1, 1)
                            helper_layout.addWidget(self.cardio_labels[j], row,
                                                    1, 1, 1)
                            helper_layout.addWidget(self.edit_buttons[j], row,
                                                    2, 1, 1)
                            helper_layout.addWidget(self.delete_buttons[j],
                                                    row, 3, 1, 1)
                            j += 1
                            row += 1

        scroll_area = QScrollArea()
        scroll_area.setContentsMargins(3, 3, 3, 3)
        scroll_area.setWidgetResizable(True)
        helper_widget = QWidget()
        helper_widget.setLayout(helper_layout)
        scroll_area.setWidget(helper_widget)
        self.layout.addWidget(scroll_area, 0, 0, 1, 1)

        close_button = QPushButton("Close")
        close_button.clicked.connect(lambda: self.close())
        self.layout.addWidget(close_button, row, 0, 1, 4)

    def edit_cardio_dialog(self, date, activity, index):
        self.edit_entry_dialog = EditCardioHistoryEntry(
            self.cardio_history, date, activity, index)
        self.edit_entry_dialog.update_cardio_history_signal.connect(
            lambda signal: self.create_history(signal))
        self.edit_entry_dialog.show()

    def delete_history(self):
        self.cardio_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "cardio_history"))
        self.refresh_cardio_labels_signal.emit(True)
        for i in reversed(range(self.layout.count())):
            self.layout.itemAt(i).widget().setParent(None)

    def delete_entry(self, j, date, activity, index):
        self.date_labels[j].setParent(None)
        self.cardio_labels[j].setParent(None)
        self.edit_buttons[j].setParent(None)
        self.delete_buttons[j].setParent(None)
        del self.cardio_history[date][activity][index]
        current_cardio_history = json.dumps(self.cardio_history)
        self.db_wrapper.update_table_column(self.table_name, "cardio_history",
                                            json.dumps(self.cardio_history))
Esempio n. 4
0
class MainPanel(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.db_wrapper = DatabaseWrapper()
        self.user_data = self.db_wrapper.fetch_local_user_info()
        self.setStyleSheet("""QWidget{
      color:#c7c7c7;
      font-weight: bold;
      font-family: Montserrat;
      font-size: 16px;
      }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QComboBox{
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
      min-height: 28px;
      background-color: #440D0F;
    }
    QComboBox:down-arrow{
      width: 0px;
      height: 0px;
      background: #d3d3d3; 
      opacity:0
    }
    QComboBox:drop-down{
      background-color: #440D0F;
      border: 0px;
      opacity:0;
      border-radius: 0px;
      width: 0px;
      height: 0px;
    }
    QComboBox:hover:!pressed{
      background-color: #5D1A1D;
    }
    QComboBox:pressed{
      background-color: #551812;
    }""")
        self.create_panel()

    def create_panel(self):
        main_panel_layout = QGridLayout()
        main_panel_layout.addWidget(self.create_top_panel(), 0, 0, 2, 1)
        main_panel_layout.addLayout(self.settings_layout(), 2, 0, 1, 1)
        self.setLayout(main_panel_layout)

    def create_top_panel(self):
        layout = QGridLayout()
        self.username_layout = QHBoxLayout()
        self.name_label = QLabel()
        self.name_label.setText(" ".join(["Username:"******"Name"]]))
        self.edit_username_button = QPushButton("Edit")
        self.edit_username_button.setFixedSize(60, 30)
        self.username_layout.addWidget(self.name_label)
        self.username_layout.addWidget(self.edit_username_button)
        self.edit_username_button.clicked.connect(
            lambda: self.update_username())

        framed_layout_username = QFrame()
        framed_layout_username.setLayout(self.username_layout)
        framed_layout_username = self.setup_frame(framed_layout_username)

        self.age_layout = QHBoxLayout()
        self.age_label = QLabel()
        self.age_label.setText(" ".join(["Age:", self.user_data["Age"]]))
        self.edit_age_button = QPushButton("Edit")
        self.edit_age_button.setFixedSize(60, 30)
        self.age_layout.addWidget(self.age_label)
        self.age_layout.addWidget(self.edit_age_button)
        self.edit_age_button.clicked.connect(lambda: self.update_age())

        framed_layout_age = QFrame()
        framed_layout_age.setLayout(self.age_layout)
        framed_layout_age = self.setup_frame(framed_layout_age)

        self.height_layout = QHBoxLayout()
        self.height_label = QLabel()
        self.height_label.setText(" ".join(
            ["Height:", self.user_data["Height"]]))
        self.edit_height_button = QPushButton("Edit")
        self.edit_height_button.setFixedSize(60, 30)
        self.height_layout.addWidget(self.height_label)
        self.height_layout.addWidget(self.edit_height_button)
        self.edit_height_button.clicked.connect(lambda: self.update_height())

        framed_layout_height = QFrame()
        framed_layout_height.setLayout(self.height_layout)
        framed_layout_height = self.setup_frame(framed_layout_height)

        self.goalw_layout = QHBoxLayout()
        self.goalw_label = QLabel()
        self.goalw_label.setText(" ".join(
            ["Goal Weight:", self.user_data["Weight Goal"]]))
        self.edit_goalw_button = QPushButton("Edit")
        self.edit_goalw_button.setFixedSize(60, 30)
        self.goalw_layout.addWidget(self.goalw_label)
        self.goalw_layout.addWidget(self.edit_goalw_button)
        self.edit_goalw_button.clicked.connect(
            lambda: self.update_goal_weight())

        framed_layout_goalw = QFrame()
        framed_layout_goalw.setLayout(self.goalw_layout)
        framed_layout_goalw = self.setup_frame(framed_layout_goalw)

        self.weight_layout = QHBoxLayout()
        self.weight_label = QLabel()
        self.weight_label.setText(" ".join(
            ["Weight:", self.user_data["Weight"]]))
        self.edit_weight_button = QPushButton("Edit")
        self.edit_weight_button.setFixedSize(60, 30)
        self.weight_layout.addWidget(self.weight_label)
        self.weight_layout.addWidget(self.edit_weight_button)
        self.edit_weight_button.clicked.connect(lambda: self.update_weight())

        framed_layout_weight = QFrame()
        framed_layout_weight.setLayout(self.weight_layout)
        framed_layout_weight = self.setup_frame(framed_layout_weight)

        self.gender_layout = QHBoxLayout()
        self.gender_label = QLabel()
        self.gender_label.setText(" ".join(
            ["Gender:", self.user_data["Gender"]]))
        self.edit_gender_button = QPushButton("Edit")
        self.edit_gender_button.setFixedSize(60, 30)
        self.gender_layout.addWidget(self.gender_label)
        self.gender_layout.addWidget(self.edit_gender_button)
        self.edit_gender_button.clicked.connect(lambda: self.update_gender())

        framed_layout_gender = QFrame()
        framed_layout_gender.setLayout(self.gender_layout)
        framed_layout_gender = self.setup_frame(framed_layout_gender)

        self.goal_layout = QHBoxLayout()
        self.goal_label = QLabel()
        self.goal_label.setText(" ".join(["Goal:", self.user_data["Goal"]]))
        self.edit_goal_button = QPushButton("Edit")
        self.edit_goal_button.setFixedSize(60, 30)
        self.goal_layout.addWidget(self.goal_label)
        self.goal_layout.addWidget(self.edit_goal_button)
        self.edit_goal_button.clicked.connect(lambda: self.update_goal())

        framed_layout_goal = QFrame()
        framed_layout_goal.setLayout(self.goal_layout)
        framed_layout_goal = self.setup_frame(framed_layout_goal)

        layout.setHorizontalSpacing(70)
        layout.addWidget(framed_layout_username, 0, 0, 1, 1)
        layout.addWidget(framed_layout_age, 1, 0, 1, 1)
        layout.addWidget(framed_layout_height, 0, 1, 1, 1)
        layout.addWidget(framed_layout_weight, 1, 1, 1, 1)
        layout.addWidget(framed_layout_goalw, 2, 0, 1, 1)
        layout.addWidget(framed_layout_gender, 2, 1, 1, 1)
        layout.addWidget(framed_layout_goal, 3, 0, 1, 1)

        framed_layout = QFrame()
        framed_layout.setLayout(layout)
        framed_layout = self.setup_frame(framed_layout)

        return framed_layout

    def setup_frame(self, frame):
        frame.setFrameStyle(QFrame.Box)
        frame.setLineWidth(3)
        frame.setObjectName("frame")
        frame.setStyleSheet("""#frame {color: #322d2d;}""")
        return frame

    def settings_layout(self):
        settings = QVBoxLayout()
        #settings_label = QLabel("Other")
        #settings_label.setFont(QFont("Ariel", 14))
        #settings.addWidget(settings_label)

        settings_layout = QHBoxLayout()
        settings_left_layout = QVBoxLayout()
        settings_right_layout = QVBoxLayout()

        display_units = QHBoxLayout()
        display_units_label = QLabel("Display Units:")
        display_units_label.setFont(QFont("Ariel", 10))
        self.display_units_combobox = QComboBox()
        self.display_units_combobox.setCursor(QCursor(Qt.PointingHandCursor))
        self.display_units_combobox.addItems(["Metric", "Imperial"])

        current_index = 0 if self.user_data["Units"] == "metric" else 1
        self.display_units_combobox.setCurrentIndex(current_index)
        if self.db_wrapper.connection_exists:
            self.display_units_combobox.activated.connect(
                lambda: self.change_units(self.display_units_combobox.
                                          currentText().lower()))

        display_units.addWidget(display_units_label)
        display_units.addWidget(self.display_units_combobox)

        app_style = QHBoxLayout()
        app_style_label = QLabel("Theme")

        settings_left_layout.addLayout(display_units)

        framed_left_layout = QFrame()
        framed_left_layout = self.setup_frame(framed_left_layout)
        framed_left_layout.setLayout(settings_left_layout)

        settings_layout.addWidget(framed_left_layout)
        settings_layout.addLayout(settings_right_layout)

        settings.addLayout(settings_layout)
        return settings

    def change_units(self, selected_units):
        current_units = self.db_wrapper.fetch_local_column("Users", "units")
        if current_units != selected_units:
            self.db_wrapper.update_table_column("Users", "units",
                                                selected_units)
            if selected_units == "imperial":
                # update height
                new_height = metric_to_imperial_height(
                    int(self.user_data["Height"]))
                self.height_label.setText(" ".join(
                    ["Height:",
                     "%s'%s''" % (new_height[0], new_height[1])]))
                self.user_data["Height"] = "%s'%s''" % (new_height[0],
                                                        new_height[1])
                self.db_wrapper.update_table_column(
                    "Users", "height",
                    "%s'%s''" % (new_height[0], new_height[1]))

                # update weight, goal weight and loss_per_week
                new_weight = kg_to_pounds(self.user_data["Weight"])
                new_goal_weight = kg_to_pounds(self.user_data["Weight Goal"])
                new_loss_per_week = kg_to_pounds(
                    self.user_data["Goal Params"][1])

                self.weight_label.setText(" ".join(
                    ["Weight:", str(new_weight)]))
                self.goalw_label.setText(" ".join(
                    ["Goal Weight:", str(new_goal_weight)]))

                self.user_data["Weight"] = new_weight
                self.user_data["Weight Goal"] = new_goal_weight
                self.user_data["Goal Params"][1] = new_loss_per_week

            elif selected_units == "metric":
                # update height
                parsed_imperial_height = self.user_data["Height"].strip(
                    "''").split("'")
                new_height = imperial_to_metric_height(
                    int(parsed_imperial_height[0]),
                    int(parsed_imperial_height[1]))
                self.height_label.setText(" ".join(
                    ["Height:", str(new_height)]))
                self.user_data["Height"] = new_height
                self.db_wrapper.update_table_column("Users", "height",
                                                    str(new_height))

                # update weight
                new_weight = pounds_to_kg(self.user_data["Weight"])
                new_goal_weight = pounds_to_kg(self.user_data["Weight Goal"])
                new_loss_per_week = pounds_to_kg(
                    self.user_data["Goal Params"][1])

                self.weight_label.setText(" ".join(
                    ["Weight:", str(new_weight)]))
                self.goalw_label.setText(" ".join(
                    ["Goal Weight:", str(new_goal_weight)]))

                self.user_data["Weight"] = new_weight
                self.user_data["Weight Goal"] = new_goal_weight
                self.user_data["Goal Params"][1] = new_loss_per_week

            self.db_wrapper.update_table_column("Users", "weight", new_weight)
            self.db_wrapper.update_table_column("Users", "goalweight",
                                                new_goal_weight)
            self.db_wrapper.update_table_column(
                "Users", "goalparams",
                json.dumps(self.user_data["Goal Params"]))

    def update_weight(self):
        global weight_edit
        weight_edit = EditButtonLine(self, "weight")
        weight_edit.show()

    def update_goal(self):
        global goal_edit
        goal_edit = EditRadioButton(self, "goal", self.user_data["Goal"])
        goal_edit.show()

    def update_height(self):
        global height_edit
        height_edit = EditButtonLine(self, "height")
        height_edit.show()

    def update_age(self):
        global age_edit
        age_edit = EditButtonLine(self, "age")
        age_edit.show()

    def update_username(self):
        global name_edit
        name_edit = EditButtonLine(self, "username")
        name_edit.show()

    def update_goal_weight(self):
        global gw_edit
        gw_edit = EditButtonLine(self, "goalweight")
        gw_edit.show()

    def update_gender(self):
        global gender_edit
        gender_edit = EditRadioButton(self, "gender", self.user_data["Gender"])
        gender_edit.show()

    def refresh_user_data(self):
        self.user_data = self.db_wrapper.fetch_local_user_info()
        self.name_label.setText(" ".join(["Username:"******"Name"]]))
        self.age_label.setText(" ".join(["Age:", self.user_data["Age"]]))
        self.height_label.setText(" ".join(
            ["Height:", self.user_data["Height"]]))
        self.goalw_label.setText(" ".join(
            ["Goal Weight:", self.user_data["Weight Goal"]]))
        self.weight_label.setText(" ".join(
            ["Weight:", self.user_data["Weight"]]))
        self.goal_label.setText(" ".join(["Goal:", self.user_data["Goal"]]))
        self.gender_label.setText(" ".join(
            ["Gender:", self.user_data["Gender"]]))
Esempio n. 5
0
class EditButtonLine(QWidget):
    def __init__(self, parent, edit_func):
        super().__init__()
        self.edit_func = edit_func
        self.this_parent = parent
        self.db_wrapper = DatabaseWrapper()
        self.setStyleSheet("""QWidget{
      background-color: #232120;
      color:#c7c7c7;
      font-weight: bold;
      font-family: Montserrat;
      font-size: 16px;
      }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QLineEdit{
      padding: 6px;
      background-color: rgb(33,33,33);
      border: 1px solid;
      border-color: #cdcdcd;
    }""")
        dialog_layout = QVBoxLayout()
        self.setWindowFlags(Qt.FramelessWindowHint)
        dialog_layout.addLayout(self.create_input_window())
        self.setLayout(dialog_layout)

    def create_input_window(self):
        layout = QVBoxLayout()
        entry_label = QLabel("Edit ")

        self.line_edit = QLineEdit()

        helper_layout = QHBoxLayout()

        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close_button())

        confirm_button = QPushButton("Confirm")
        if self.edit_func == "weight":
            self.line_edit.setValidator(QDoubleValidator())
            entry_label.setText("Weight")
            confirm_button.clicked.connect(lambda: self.confirm_weight())
        elif self.edit_func == "height":
            self.line_edit.setValidator(QDoubleValidator())
            entry_label.setText("Height")
            confirm_button.clicked.connect(lambda: self.confirm_height())
        elif self.edit_func == "age":
            self.line_edit.setValidator(QDoubleValidator())
            entry_label.setText("Age")
            confirm_button.clicked.connect(lambda: self.confirm_age())
        elif self.edit_func == "goalweight":
            self.line_edit.setValidator(QDoubleValidator())
            entry_label.setText("Goal Weight")
            confirm_button.clicked.connect(lambda: self.confirm_goal_weight())
        elif self.edit_func == "username":
            entry_label.setText("Username")
            confirm_button.clicked.connect(lambda: self.confirm_name())

        helper_layout.addWidget(cancel_button)
        helper_layout.addWidget(confirm_button)

        layout.addWidget(entry_label)
        layout.addWidget(self.line_edit)
        layout.addLayout(helper_layout)

        return layout

    def close_button(self):
        self.close()

    def confirm_height(self):
        if self.line_edit.text() != "":
            self.db_wrapper.update_table_column("Users", "height",
                                                self.line_edit.text())
            self.this_parent.refresh_user_data()
            self.close()

    def confirm_weight(self):
        if self.line_edit.text() != "":
            self.db_wrapper.update_table_column("Users", "weight",
                                                self.line_edit.text())
            self.this_parent.refresh_user_data()
            self.close()

    def confirm_age(self):
        if self.line_edit.text() != "":
            self.db_wrapper.update_table_column("Users", "age",
                                                self.line_edit.text())
            self.this_parent.refresh_user_data()
            self.close()

    def confirm_name(self):
        if self.line_edit.text() != "":
            self.db_wrapper.update_table_column("Users", "name",
                                                self.line_edit.text())
            self.this_parent.refresh_user_data()
            self.close()

    def confirm_goal_weight(self):
        if self.line_edit.text() != "":
            self.db_wrapper.update_table_column("Users", "goalweight",
                                                self.line_edit.text())
            self.this_parent.refresh_user_data()
            self.close()
Esempio n. 6
0
class ChangeWeightDialog(QWidget):
    change_current_weight_signal = pyqtSignal(str)
    change_goal_weight_signal = pyqtSignal(str)
    change_calorie_goal_signal = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Nutrition"
        self.user_data = self.db_wrapper.fetch_local_user_info()
        self.user_weight = self.user_data["Weight"]
        self.goal_weight = self.user_data["Weight Goal"]
        goal_parameters = self.user_data["Goal Params"]
        self.goal = self.user_data["Goal"]
        self.activity_level = goal_parameters[0]
        self.weight_per_week = goal_parameters[1]
        self.age = self.user_data["Age"]
        self.gender = self.user_data["Gender"]
        self.height = self.user_data["Height"]
        self.setWindowTitle("Edit weight")
        self.create_layout()

    def create_layout(self):
        layout = QFormLayout()

        current_weight_label = QLabel("Current weight")
        self.current_weight_line_edit = QLineEdit()
        self.current_weight_line_edit.setText(self.user_weight)

        goal_label = QLabel("Goal")
        goal_layout = QHBoxLayout()
        goal = QGroupBox()
        self.weight_loss_button = QRadioButton("Weight loss")
        self.maintain_weight_button = QRadioButton("Maintain weight")
        self.weight_gain_button = QRadioButton("Weight gain")
        if self.goal == "Weight loss": self.weight_loss_button.setChecked(True)
        elif self.goal == "Maintain weight":
            self.maintain_weight_button.setChecked(True)
        elif self.goal == "Weight gain":
            self.weight_gain_button.setChecked(True)
        goal_layout.addWidget(self.weight_loss_button)
        goal_layout.addWidget(self.maintain_weight_button)
        goal_layout.addWidget(self.weight_gain_button)
        goal.setLayout(goal_layout)

        goal_parameters_label = QLabel("Goal parameters")
        goal_parameters_layout = QHBoxLayout()

        activity_level_layout = QVBoxLayout()
        activity_level_label = QLabel("Activity level")
        self.activity_level_cb = QComboBox()
        self.activity_level_cb.addItems([
            "Sedentary", "Lightly active", "Moderately active", "Very active",
            "Extra active"
        ])
        self.activity_level_cb.setCurrentText(self.activity_level)
        activity_level_layout.addWidget(activity_level_label)
        activity_level_layout.addWidget(self.activity_level_cb)

        weight_per_week_layout = QVBoxLayout()
        weight_per_week_label = QLabel("Weight to lose/gain per week (kg)")
        self.weight_per_week_cb = QComboBox()
        self.weight_per_week_cb.addItems(["0.25", "0.5", "1"])
        self.weight_per_week_cb.setCurrentText(str(self.weight_per_week))
        weight_per_week_layout.addWidget(weight_per_week_label)
        weight_per_week_layout.addWidget(self.weight_per_week_cb)

        goal_parameters_layout.addLayout(activity_level_layout)
        goal_parameters_layout.addLayout(weight_per_week_layout)

        goal_weight_label = QLabel("Goal weight")
        self.goal_weight_line_edit = QLineEdit()
        self.goal_weight_line_edit.setText(self.goal_weight)

        save_changes_button = QPushButton("Save changes")
        save_changes_button.clicked.connect(lambda: self.save_changes())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close())

        layout.addRow(current_weight_label, self.current_weight_line_edit)
        layout.addRow(goal_label, goal)
        layout.addRow(goal_parameters_label, goal_parameters_layout)
        layout.addRow(goal_weight_label, self.goal_weight_line_edit)
        layout.addRow(save_changes_button, cancel_button)
        self.setLayout(layout)

    def save_changes(self):
        current_weight = str(float(self.current_weight_line_edit.text()))
        if self.weight_loss_button.isChecked():
            goal = "Weight loss"
        elif self.maintain_weight_button.isChecked():
            goal = "Maintain weight"
        elif self.weight_gain_button.isChecked():
            goal = "Weight gain"
        goal_params = [
            self.activity_level_cb.currentText(),
            float(self.weight_per_week_cb.currentText())
        ]
        goal_weight = str(float(self.goal_weight_line_edit.text()))

        try:
            if not current_weight == self.user_weight:
                self.db_wrapper.update_table_column("Users", "weight",
                                                    str(float(current_weight)))
                self.user_weight = current_weight
                self.change_current_weight_signal.emit(current_weight)
                self.current_weight_line_edit.setText(current_weight)
            if not goal == self.goal:
                self.db_wrapper.update_table_column("Users", "goal", goal)
                self.goal = goal
                if goal == "Weight loss":
                    self.weight_loss_button.setChecked(True)
                elif goal == "Maintain weight":
                    self.maintain_weight_button.setChecked(True)
                elif goal == "Weight gain":
                    self.weight_gain_button.setChecked(True)
            if not goal_params[0] == self.activity_level or not goal_params[
                    1] == self.weight_per_week:
                self.db_wrapper.update_table_column("Users", "goalparams",
                                                    goal_params)
                self.activity_level = goal_params[0]
                self.weight_per_week = goal_params[1]
            if not goal_weight == self.goal_weight:
                self.db_wrapper.update_table_column("Users", "goalweight",
                                                    goal_weight)
                self.goal_weight = goal_weight
                self.change_goal_weight_signal.emit(goal_weight)
                self.goal_weight_line_edit.setText(goal_weight)

            calculator = CalorieGoalCalculator(int(self.age), self.gender,
                                               float(self.height),
                                               float(self.user_weight),
                                               goal_params[0], goal,
                                               goal_params[1])
            calorie_goal = calculator.calculate_calorie_goal()
            self.db_wrapper.update_table_column(self.table_name,
                                                "calorie_goal", goal_weight)
            self.change_calorie_goal_signal.emit(str(calorie_goal))
            self.close()
        except ValueError:
            pass
class UpdateLiftsForRepsWindow(QWidget):
    change_lifts_for_reps_signal = pyqtSignal(bool)
    history_signal = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Compound Exercises"
        self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        self.preferred_lifts = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "preferred_lifts"))
        self.setWindowTitle("Update Lifts For Reps")
        self.setLayout(self.create_panel())
        self.set_line_edit_values()

    def create_panel(self):
        form_layout = QFormLayout()

        exercise_label = QLabel("Exercise")
        header_layout = QHBoxLayout()
        reps_label = QLabel("Reps")
        weight_label = QLabel("Weight")
        header_layout.addWidget(reps_label)
        header_layout.addWidget(weight_label)

        horizontal_press_label = QLabel(
            self.preferred_lifts["Horizontal Press"])
        self.horizontal_press_reps_edit = QLineEdit()
        self.horizontal_press_reps_edit.setValidator(QIntValidator())
        x_label = QLabel("x")
        self.horizontal_press_edit = QLineEdit()
        self.horizontal_press_edit.setValidator(QIntValidator())
        units_label = QLabel(self.units)
        hbox = QHBoxLayout()
        hbox.addWidget(self.horizontal_press_reps_edit)
        hbox.addWidget(x_label)
        hbox.addWidget(self.horizontal_press_edit)
        hbox.addWidget(units_label)

        floor_pull_label = QLabel(self.preferred_lifts["Floor Pull"])
        self.floor_pull_reps_edit = QLineEdit()
        self.floor_pull_reps_edit.setValidator(QIntValidator())
        x_label1 = QLabel("x")
        self.floor_pull_edit = QLineEdit()
        self.floor_pull_edit.setValidator(QIntValidator())
        units_label1 = QLabel(self.units)
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.floor_pull_reps_edit)
        hbox1.addWidget(x_label1)
        hbox1.addWidget(self.floor_pull_edit)
        hbox1.addWidget(units_label1)

        squat_label = QLabel(self.preferred_lifts["Squat"])
        self.squat_reps_edit = QLineEdit()
        self.squat_reps_edit.setValidator(QIntValidator())
        x_label2 = QLabel("x")
        self.squat_edit = QLineEdit()
        self.squat_edit.setValidator(QIntValidator())
        units_label2 = QLabel(self.units)
        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.squat_reps_edit)
        hbox2.addWidget(x_label2)
        hbox2.addWidget(self.squat_edit)
        hbox2.addWidget(units_label2)

        vertical_press_label = QLabel("Overhead Press")
        self.vertical_press_reps_edit = QLineEdit()
        self.vertical_press_reps_edit.setValidator(QIntValidator())
        x_label3 = QLabel("x")
        self.vertical_press_edit = QLineEdit()
        self.vertical_press_edit.setValidator(QIntValidator())
        units_label3 = QLabel(self.units)
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.vertical_press_reps_edit)
        hbox3.addWidget(x_label3)
        hbox3.addWidget(self.vertical_press_edit)
        hbox3.addWidget(units_label3)

        buttons_layout = QHBoxLayout()
        save_button = QPushButton("Save")
        save_button.clicked.connect(lambda: self.save_lifts_for_reps())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(
            lambda: self.close_update_lifts_for_reps())
        buttons_layout.addWidget(save_button)
        buttons_layout.addWidget(cancel_button)

        form_layout.addRow(exercise_label, header_layout)
        form_layout.addRow(horizontal_press_label, hbox)
        form_layout.addRow(floor_pull_label, hbox1)
        form_layout.addRow(squat_label, hbox2)
        form_layout.addRow(vertical_press_label, hbox3)

        main_layout = QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addLayout(buttons_layout)

        return main_layout

    def save_lifts_for_reps(self):
        try:
            fetched_lifts_for_reps = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "lifts_for_reps"))
            exercises = list(fetched_lifts_for_reps.keys())
            horizontal_press_weight = str(
                float(self.horizontal_press_edit.text()))
            floor_pull_weight = str(float(self.floor_pull_edit.text()))
            squat_weight = str(float(self.squat_edit.text()))
            vertical_press_weight = str(float(self.vertical_press_edit.text()))

            horizontal_press_reps = str(
                float(self.horizontal_press_reps_edit.text()))
            floor_pull_reps = str(float(self.floor_pull_reps_edit.text()))
            squat_reps = str(float(self.squat_reps_edit.text()))
            vertical_press_reps = str(
                float(self.vertical_press_reps_edit.text()))

            new_lifts_for_reps = {
                exercises[0]: [horizontal_press_reps, horizontal_press_weight],
                exercises[1]: [floor_pull_reps, floor_pull_weight],
                exercises[2]: [squat_reps, squat_weight],
                exercises[3]: [vertical_press_reps, vertical_press_weight]
            }
            diff = self.lift_difference(new_lifts_for_reps,
                                        fetched_lifts_for_reps,
                                        lifts_reps=True)
            self.db_wrapper.update_table_column(self.table_name,
                                                "lift_history", diff)
            self.history_signal.emit(True)
            self.db_wrapper.update_table_column(self.table_name,
                                                "lifts_for_reps",
                                                new_lifts_for_reps)
            self.change_lifts_for_reps_signal.emit(True)
            self.set_line_edit_values()
            self.close()
        except ValueError:
            pass

    def close_update_lifts_for_reps(self):
        self.close()
        self.set_line_edit_values()

    def set_line_edit_values(self):
        lift_values = list(
            json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "lifts_for_reps")).values())
        reps = [lift[0] for lift in lift_values]
        weight = [lift[1] for lift in lift_values]

        reps_line_edit = [
            self.horizontal_press_reps_edit, self.floor_pull_reps_edit,
            self.squat_reps_edit, self.vertical_press_reps_edit
        ]

        weight_line_edit = [
            self.horizontal_press_edit, self.floor_pull_edit, self.squat_edit,
            self.vertical_press_edit
        ]

        for i, line_edit in enumerate(reps_line_edit):
            line_edit.setText(reps[i])

        for i, line_edit in enumerate(weight_line_edit):
            line_edit.setText(weight[i])

    def sort_exercises(self, exercise):
        if exercise in ["Bench Press", "Incline Bench Press"]: return 4
        elif exercise in ["Deadlift", "Sumo Deadlift"]: return 3
        elif exercise in ["Back Squat", "Front Squat"]: return 2
        elif exercise in ["Overhead Press", "Push Press"]: return 1

    # returns sorted dictionary containing updated lifts
    def lift_difference(self,
                        new_lifts,
                        old_lifts,
                        one_RM=False,
                        lifts_reps=False):
        difference = None
        if one_RM:
            db_lifts = set(": ".join([exercise, weight])
                           for exercise, weight in old_lifts.items())
            new_lifts = set(": ".join([exercise, weight])
                            for exercise, weight in new_lifts.items()
                            if not weight == '0.0')
            diff = list(new_lifts.difference(
                db_lifts))  # local lifts that are not in db
            difference = {
                exercise.split(": ")[0]: exercise.split(": ")[1]
                for exercise in diff
            }
        elif lifts_reps:
            db_lifts = set(":".join([exercise, "x".join(values)])
                           for exercise, values in old_lifts.items())
            new_lifts = set(":".join([exercise, "x".join(values)])
                            for exercise, values in new_lifts.items()
                            if not values[1] == '0.0')
            diff = list(new_lifts.difference(db_lifts))
            difference = {
                exercise.split(":")[0]: exercise.split(":")[1].split("x")
                for exercise in diff
            }
        return {
            key: value
            for key, value in sorted(
                difference.items(),
                key=lambda exercise: self.sort_exercises(exercise[0]))
        }
Esempio n. 8
0
class PreferredLifts(QWidget):
    change_lifts_signal = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Compound Exercises"
        self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;      
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QComboBox{
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
      min-height: 28px;
      background-color: #440D0F;
    }
    QComboBox:down-arrow{
      width: 0px;
      height: 0px;
      background: #d3d3d3; 
      opacity:0
    }
    QComboBox:drop-down{
      background-color: #440D0F;
      border: 0px;
      opacity:0;
      border-radius: 0px;
      width: 0px;
      height: 0px;
    }
    QComboBox:hover:!pressed{
      background-color: #5D1A1D;
    }
    QComboBox:pressed{
      background-color: #551812;
    }
    """)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("Edit Preferred Lifts")
        self.preferred_lifts = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "preferred_lifts"))
        self.setLayout(self.create_panel())
        self.set_preferred_lifts()

    def create_panel(self):
        form_layout = QFormLayout()

        horizontal_press_label = QLabel("Horizontal Press")
        self.horizontal_press_dropdown = QComboBox()
        self.horizontal_press_dropdown.addItems(
            ["Bench Press", "Incline Bench Press"])

        floor_pull_label = QLabel("Floor Pull")
        self.floor_pull_dropdown = QComboBox()
        self.floor_pull_dropdown.addItems(["Deadlift", "Sumo Deadlift"])

        squat_label = QLabel("Squat")
        self.squat_dropdown = QComboBox()
        self.squat_dropdown.addItems(["Back Squat", "Front Squat"])

        vertical_press_label = QLabel("Vertical Press")
        self.vertical_press_dropdown = QComboBox()
        self.vertical_press_dropdown.addItems(["Overhead Press", "Push Press"])

        buttons_layout = QHBoxLayout()
        save_button = QPushButton("Save")
        save_button.clicked.connect(lambda: self.save_preferred_lifts())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close())
        buttons_layout.addWidget(save_button)
        buttons_layout.addWidget(cancel_button)

        form_layout.addRow(horizontal_press_label,
                           self.horizontal_press_dropdown)
        form_layout.addRow(floor_pull_label, self.floor_pull_dropdown)
        form_layout.addRow(squat_label, self.squat_dropdown)
        form_layout.addRow(vertical_press_label, self.vertical_press_dropdown)

        main_layout = QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addLayout(buttons_layout)

        return main_layout

    def set_preferred_lifts(self):
        horizontal_press_index = self.horizontal_press_dropdown.findText(
            self.preferred_lifts["Horizontal Press"])
        floor_pull_index = self.floor_pull_dropdown.findText(
            self.preferred_lifts["Floor Pull"])
        squat_index = self.squat_dropdown.findText(
            self.preferred_lifts["Squat"])
        vertical_press_index = self.vertical_press_dropdown.findText(
            self.preferred_lifts["Vertical Press"])

        self.horizontal_press_dropdown.setCurrentIndex(horizontal_press_index)
        self.floor_pull_dropdown.setCurrentIndex(floor_pull_index)
        self.squat_dropdown.setCurrentIndex(squat_index)
        self.vertical_press_dropdown.setCurrentIndex(vertical_press_index)

    def save_preferred_lifts(self):
        horizontal_press = str(self.horizontal_press_dropdown.currentText())
        floor_pull = str(self.floor_pull_dropdown.currentText())
        squat = str(self.squat_dropdown.currentText())
        vertical_press = str(self.vertical_press_dropdown.currentText())
        new_preferred_lifts = {
            "Horizontal Press": horizontal_press,
            "Floor Pull": floor_pull,
            "Squat": squat,
            "Vertical Press": vertical_press
        }
        self.db_wrapper.update_table_column(self.table_name, "preferred_lifts",
                                            new_preferred_lifts)

        new_preferred_lifts = list(new_preferred_lifts.values())
        one_rep_maxes = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "one_rep_maxes"))
        lifts_for_reps = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "lifts_for_reps"))

        new_one_rep_maxes = {
            new_preferred_lifts[i]: value
            for i, value in enumerate(one_rep_maxes.values())
        }
        new_lifts_for_reps = {
            new_preferred_lifts[i]: value
            for i, value in enumerate(lifts_for_reps.values())
        }

        self.db_wrapper.update_table_column(self.table_name, "one_rep_maxes",
                                            new_one_rep_maxes)
        self.db_wrapper.update_table_column(self.table_name, "lifts_for_reps",
                                            new_lifts_for_reps)

        self.change_lifts_signal.emit(True)
        self.close()
Esempio n. 9
0
class MainPanel(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Weight Loss"
        self.setStyleSheet("""
    QWidget{
      color:#c7c7c7;
      font-weight: bold;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QComboBox{
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
      min-height: 28px;
      background-color: #440D0F;
    }
    QComboBox:down-arrow{
      width: 0px;
      height: 0px;
      background: #d3d3d3; 
      opacity:0
    }
    QComboBox:drop-down{
      background-color: #440D0F;
      border: 0px;
      opacity:0;
      border-radius: 0px;
      width: 0px;
      height: 0px;
    }
    QComboBox:hover:!pressed{
      background-color: #5D1A1D;
    }
    QComboBox:pressed{
      background-color: #551812;
    }
    """)

        self.db_wrapper.create_local_table(self.table_name)
        self.db_wrapper.create_local_table("Nutrition")

        if self.db_wrapper.local_table_is_empty("Nutrition"):
            self.db_wrapper.insert_default_values("Nutrition")

        if self.db_wrapper.local_table_is_empty(self.table_name):
            self.db_wrapper.insert_default_values(self.table_name)

        self.fetch_user_data()
        self.date = datetime.today().strftime("%d/%m/%Y")
        self.current_year = datetime.today().year
        self.calorie_goal = self.db_wrapper.fetch_local_column(
            "Nutrition", "calorie_goal")

        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        weight_loss_units = "kg" if self.db_wrapper.fetch_local_column(
            self.table_name, "units") == "metric" else "lb"
        self.weight_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "weight_history"))

        if self.units != weight_loss_units:
            units_name = "metric" if self.units == "kg" else "imperial"
            self.db_wrapper.update_table_column(self.table_name, "units",
                                                units_name)
            if units_name == "metric":
                for date in self.weight_history:
                    self.weight_history[date] = str(
                        pounds_to_kg(self.weight_history[date]))

            elif units_name == "imperial":
                for date in self.weight_history:
                    self.weight_history[date] = str(
                        kg_to_pounds(self.weight_history[date]))

            self.db_wrapper.update_table_column(
                self.table_name, "weight_history",
                json.dumps(self.weight_history))

        self.preferred_activity = self.db_wrapper.fetch_local_column(
            self.table_name, "preferred_activity")
        self.cardio_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "cardio_history"))
        if not self.date in self.cardio_history:
            self.add_date_to_cardio_history()
        if not self.date in self.weight_history:
            self.add_date_to_weight_history()

        self.init_cardio_labels()
        self.create_panel()

    def create_panel(self):
        grid = QGridLayout()
        grid.addLayout(self.create_description(), 0, 0, 1, 1)
        grid.addWidget(self.create_graph(), 1, 0, 4, 1)
        grid.addLayout(self.create_bottom_layout(), 5, 0, 3, 1)
        self.setLayout(grid)

    def create_description(self):
        description = QVBoxLayout()
        description_font = QFont("Montserrat", 12)
        description_label = QLabel(
            "Keep notes and track your weight loss journey.", self)
        description_label.setFont(description_font)
        description_label.setFixedHeight(20)
        description.addWidget(description_label)
        return description

    def create_graph(self):
        self.graph_layout = QVBoxLayout()

        graph = WeightLossGraphCanvas(
            self.db_wrapper.months[datetime.today().month - 1],
            self.current_year, self)
        toolbar = NavigationToolbar(graph, self)
        toolbar.setStyleSheet("background-color: white;")

        combobox_layout = QHBoxLayout()
        self.months_combobox = QComboBox()

        months = []
        for entry in self.weight_history:
            month = entry.split("/")[1]
            for month_name, code in self.db_wrapper.months_mappings.items():
                if code == month: month = month_name
            if not month in months:
                months.append(month)
        if len(months) == 0:
            months.append(self.db_wrapper.months[datetime.today().month - 1])
        self.months_combobox.addItems(months)
        self.months_combobox.setCurrentText(
            self.db_wrapper.months[datetime.today().month - 1])
        self.months_combobox.currentTextChanged.connect(
            lambda month: self.change_month_graph(month))

        self.change_year_combobox = QComboBox()

        years = []
        for entry in self.weight_history:
            if not entry.split("/")[-1] in years:
                years.append(entry.split("/")[-1])
        if len(years) == 0: years.append(str(self.current_year))
        self.change_year_combobox.addItems(list(reversed(years)))
        self.change_year_combobox.currentTextChanged.connect(
            lambda year: self.change_year_graph(year))

        combobox_layout.addWidget(self.months_combobox)
        combobox_layout.addWidget(self.change_year_combobox)

        self.graph_layout.addWidget(toolbar)
        self.graph_layout.addWidget(graph)
        self.graph_layout.addLayout(combobox_layout)

        framed_graph = QFrame(self)
        framed_graph.setFrameStyle(QFrame.Box)
        framed_graph.setLineWidth(3)
        framed_graph.setLayout(self.graph_layout)

        return framed_graph

    def create_bottom_layout(self):
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(self.create_weight_loss())
        bottom_layout.addWidget(self.create_cardio_notes())
        return bottom_layout

    def create_weight_loss(self):
        weight_loss = QVBoxLayout()
        main_label = QLabel("Weight Loss")
        main_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        current_weight_layout = QHBoxLayout()
        self.current_weight_label = QLabel(" ".join(
            ["Current Weight:", self.current_weight, self.units]))
        update_current_weight_button = QPushButton("Update")
        update_current_weight_button.clicked.connect(
            lambda: self.update_value("Current Weight", self.current_weight))
        current_weight_layout.addWidget(self.current_weight_label)
        current_weight_layout.addWidget(update_current_weight_button)

        weight_goal_layout = QHBoxLayout()
        self.weight_goal_label = QLabel(" ".join(
            ["Weight Goal:", self.goal_weight, self.units]))
        update_weight_goal_label = QPushButton("Update")
        update_weight_goal_label.clicked.connect(
            lambda: self.update_value("Weight Goal", self.goal_weight))
        weight_goal_layout.addWidget(self.weight_goal_label)
        weight_goal_layout.addWidget(update_weight_goal_label)

        loss_per_week_layout = QHBoxLayout()
        self.loss_per_week_label = QLabel(" ".join(
            ["Loss Per Week:",
             str(self.loss_per_week), self.units]))
        update_loss_per_week_label = QPushButton("Update")
        update_loss_per_week_label.clicked.connect(
            lambda: self.update_value("Loss Per Week", self.loss_per_week))
        loss_per_week_layout.addWidget(self.loss_per_week_label)
        loss_per_week_layout.addWidget(update_loss_per_week_label)

        calorie_intake_layout = QHBoxLayout()
        calorie_intake_label = QLabel(" ".join(
            ["Calorie Intake:",
             str(self.calorie_goal), "kcal"]))
        calorie_intake_layout.addWidget(calorie_intake_label)

        history_layout = QHBoxLayout()
        weight_loss_history_button = QPushButton("History")
        weight_loss_history_button.clicked.connect(
            lambda: self.show_weight_history())
        history_layout.addWidget(weight_loss_history_button)

        weight_loss.addWidget(main_label)
        weight_loss.addLayout(calorie_intake_layout)
        weight_loss.addLayout(current_weight_layout)
        weight_loss.addLayout(weight_goal_layout)
        weight_loss.addLayout(loss_per_week_layout)
        weight_loss.addLayout(history_layout)

        weight_loss.setSpacing(5)
        framed_layout = QFrame()
        framed_layout.setObjectName("graphObj")
        framed_layout.setFrameStyle(QFrame.Box)
        framed_layout.setLineWidth(3)
        framed_layout.setStyleSheet("""#graphObj {color: #322d2d;}""")

        framed_layout.setLayout(weight_loss)

        return framed_layout

    def create_cardio_notes(self):
        cardio_notes = QVBoxLayout()
        main_label = QLabel("Cardio Notes")
        main_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        preferred_activity_layout = QHBoxLayout()
        self.preferred_activity_label = QLabel(" ".join(
            ["Preferred Activity:", self.preferred_activity]))
        self.preferred_activity_dropdown = QComboBox()
        self.preferred_activity_dropdown.addItems(
            ["Running", "Walking", "Cycling", "Swimming"])
        self.preferred_activity_dropdown.setCurrentText(
            self.preferred_activity)
        self.preferred_activity_dropdown.currentTextChanged.connect(
            lambda activity: self.set_new_preferred_activity(activity))

        preferred_activity_layout.addWidget(self.preferred_activity_label)
        preferred_activity_layout.addWidget(self.preferred_activity_dropdown)

        time_spent_layout = QHBoxLayout()
        self.time_spent_label = QLabel(" ".join(
            ["Time Spent:", self.time_spent, "min"]))
        update_time_spent_label = QPushButton("Update")
        update_time_spent_label.clicked.connect(
            lambda: self.update_value("Time Spent", self.time_spent))
        time_spent_layout.addWidget(self.time_spent_label)
        time_spent_layout.addWidget(update_time_spent_label)

        calories_burnt_layout = QHBoxLayout()
        self.calories_burnt_label = QLabel(" ".join(
            ["Calories Burnt:", self.calories_burnt, "kcal"]))
        update_calories_burnt_label = QPushButton("Update")
        update_calories_burnt_label.clicked.connect(
            lambda: self.update_value("Calories Burnt", self.calories_burnt))
        calories_burnt_layout.addWidget(self.calories_burnt_label)
        calories_burnt_layout.addWidget(update_calories_burnt_label)

        distance_travelled_layout = QHBoxLayout()
        self.distance_travelled_label = QLabel(" ".join(
            ["Distance Travelled:", self.distance_travelled, "m"]))
        update_distance_travelled_label = QPushButton("Update")
        update_distance_travelled_label.clicked.connect(
            lambda: self.update_value("Distance Travelled", self.
                                      distance_travelled))
        distance_travelled_layout.addWidget(self.distance_travelled_label)
        distance_travelled_layout.addWidget(update_distance_travelled_label)

        history_layout = QHBoxLayout()
        cardio_history_button = QPushButton("History")
        cardio_history_button.clicked.connect(
            lambda: self.show_cardio_history())
        self.save_changes_cardio_button = QPushButton("Save Changes")
        self.save_changes_cardio_button.clicked.connect(
            lambda: self.add_cardio_entry_to_cardio_history())
        history_layout.addWidget(cardio_history_button)
        history_layout.addWidget(self.save_changes_cardio_button)

        cardio_notes.addWidget(main_label)
        cardio_notes.addLayout(preferred_activity_layout)
        cardio_notes.addLayout(time_spent_layout)
        cardio_notes.addLayout(distance_travelled_layout)
        cardio_notes.addLayout(calories_burnt_layout)
        cardio_notes.addLayout(history_layout)

        cardio_notes.setSpacing(5)
        framed_layout = QFrame()
        framed_layout.setObjectName("graphObj")
        framed_layout.setFrameStyle(QFrame.Box)
        framed_layout.setLineWidth(3)
        framed_layout.setStyleSheet("""#graphObj {color: #322d2d;}""")

        framed_layout.setLayout(cardio_notes)

        return framed_layout

    def update_value(self, to_edit, old_value):
        fitness_goal = None
        date = None
        if not to_edit == "Calories Burnt":
            if to_edit == "Loss Per Week":
                fitness_goal = self.user_data["Goal Params"][0]
            elif to_edit == "Current Weight":
                date = self.date
            self.dialog = WeightLossEditDialog(to_edit, old_value,
                                               fitness_goal, date)
            self.dialog.update_label_signal.connect(
                lambda label_to_update: self.update_weight_loss_label(
                    label_to_update))
            self.dialog.update_cardio_notes_signal.connect(
                lambda value_to_update: self.update_cardio_notes_label(
                    to_edit, value_to_update))
            self.dialog.update_graph_signal.connect(
                lambda signal: self.refresh_graph(signal))
        else:
            self.dialog = CaloriesBurntDialog(to_edit, old_value,
                                              self.time_spent,
                                              self.distance_travelled,
                                              self.preferred_activity,
                                              self.current_weight)
            self.dialog.update_calories_label_signal.connect(
                lambda value_to_update: self.update_cardio_notes_label(
                    to_edit, value_to_update))
        self.dialog.show()

    @pyqtSlot(bool)
    def update_weight_loss_label(self, signal):
        if signal:
            self.fetch_user_data()
            self.current_weight_label.setText(" ".join(
                ["Current Weight:",
                 str(self.current_weight), self.units]))
            self.weight_goal_label.setText(" ".join(
                ["Weight Goal:",
                 str(self.goal_weight), self.units]))
            self.loss_per_week_label.setText(" ".join(
                ["Loss Per Week:",
                 str(self.loss_per_week), self.units]))

    @pyqtSlot(str)
    def update_cardio_notes_label(self, to_edit, value_to_update):
        if to_edit == "Time Spent":
            self.time_spent = value_to_update
            self.time_spent_label.setText(" ".join(
                ["Time Spent:", str(value_to_update), "min"]))
        elif to_edit == "Distance Travelled":
            self.distance_travelled = value_to_update
            self.distance_travelled_label.setText(" ".join(
                ["Distance Travelled:",
                 str(value_to_update), "m"]))
        elif to_edit == "Calories Burnt":
            self.calories_burnt = value_to_update
            self.calories_burnt_label.setText(" ".join(
                ["Calories Burnt",
                 str(value_to_update), "kcal"]))

    def fetch_user_data(self):
        self.user_data = self.db_wrapper.fetch_local_user_info()
        self.current_weight = self.user_data["Weight"]
        self.goal_weight = self.user_data["Weight Goal"]
        self.loss_per_week = self.user_data["Goal Params"][1]

    def show_weight_history(self):
        self.history = WeightLossHistory()
        self.history.update_weight_loss_label_signal.connect(
            lambda signal: self.update_weight_loss_label(signal))
        self.history.setGeometry(100, 200, 300, 300)
        self.history.show()

    def show_cardio_history(self):
        self.cardio_history_dialog = CardioHistory()
        self.cardio_history_dialog.refresh_cardio_labels_signal.connect(
            lambda signal: self.refresh_cardio_notes(signal))
        self.cardio_history_dialog.setGeometry(100, 200, 300, 300)
        self.cardio_history_dialog.show()

    @pyqtSlot(bool)
    def refresh_cardio_notes(self, signal):
        if signal:
            self.cardio_history = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "cardio_history"))
            self.init_cardio_labels()
            self.time_spent_label.setText(" ".join(
                ["Time Spent:", self.time_spent, "min"]))
            self.distance_travelled_label.setText(" ".join(
                ["Distance Travelled:", self.distance_travelled, "m"]))
            self.calories_burnt_label.setText(" ".join(
                ["Calories Burnt:", self.calories_burnt, "kcal"]))

    def set_new_preferred_activity(self, activity):
        self.preferred_activity = activity
        self.preferred_activity_label.setText(" ".join(
            ["Preferred Activity:", activity]))
        self.preferred_activity_dropdown.setCurrentText(activity)
        self.db_wrapper.update_table_column(self.table_name,
                                            "preferred_activity",
                                            self.preferred_activity)
        self.init_cardio_labels()
        self.time_spent_label.setText(" ".join(
            ["Time Spent:", self.time_spent, "min"]))
        self.distance_travelled_label.setText(" ".join(
            ["Distance Travelled:", self.distance_travelled, "m"]))
        self.calories_burnt_label.setText(" ".join(
            ["Calories Burnt:", self.calories_burnt, "kcal"]))

    def init_cardio_labels(self):
        if len(self.cardio_history[self.date][self.preferred_activity]) > 0:
            self.today_exercise = self.cardio_history[self.date][
                self.preferred_activity][-1]
            self.time_spent = self.today_exercise["Time Spent"]
            self.distance_travelled = self.today_exercise["Distance Travelled"]
            self.calories_burnt = self.today_exercise["Calories Burnt"]
        else:
            self.time_spent = "0"
            self.distance_travelled = "0"
            self.calories_burnt = "0"

    def add_date_to_cardio_history(self):
        activities = ["Running", "Walking", "Cycling", "Swimming"]
        self.cardio_history[self.date] = {}
        for activity in activities:
            self.cardio_history[self.date][activity] = []

        cardio_history = json.dumps(self.cardio_history)
        self.db_wrapper.update_table_column(self.table_name, "cardio_history",
                                            cardio_history)

    def add_cardio_entry_to_cardio_history(self):
        date = datetime.today().strftime("%d/%m/%Y")
        new_entry = {
            "Time Spent": str(self.time_spent),
            "Distance Travelled": str(self.distance_travelled),
            "Calories Burnt": str(self.calories_burnt)
        }
        self.cardio_history[date][self.preferred_activity].append(new_entry)
        current_cardio_history = json.dumps(self.cardio_history)
        self.db_wrapper.update_table_column(self.table_name, "cardio_history",
                                            current_cardio_history)

    def add_date_to_weight_history(self):
        try:
            last_entry = list(self.weight_history.values())[-1]
            self.weight_history[self.date] = last_entry
            self.db_wrapper.update_table_column(
                self.table_name, "weight_history",
                json.dumps(self.weight_history))
        except IndexError:  # no records
            pass

    @pyqtSlot(bool)
    def refresh_graph(self, signal):
        if signal:
            self.weight_history = self.db_wrapper.fetch_local_column(
                self.table_name, "weight_history")
            self.replace_graph(str(self.months_combobox.currentText()))

    def replace_graph(self, month):
        new_graph = WeightLossGraphCanvas(month, self.current_year, self)
        new_toolbar = NavigationToolbar(new_graph, self)

        old_toolbar_reference = self.graph_layout.itemAt(0).widget()
        old_graph_reference = self.graph_layout.itemAt(1).widget()

        self.graph_layout.replaceWidget(old_toolbar_reference, new_toolbar)
        self.graph_layout.replaceWidget(old_graph_reference, new_graph)

    def change_year_graph(self, year):
        self.current_year = year
        self.replace_graph(str(self.months_combobox.currentText()))

    def change_month_graph(self, month):
        self.replace_graph(str(month))
Esempio n. 10
0
class MainPanel(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Compound Exercises"
        self.setStyleSheet("""
    QWidget{
      color:#c7c7c7;
      font-weight: bold;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QComboBox{
      border-radius: 4px;
      font-size: 18px;
      font-weight: bold;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
      min-height: 28px;
      background-color: #440D0F;
    }
    QComboBox:down-arrow{
      width: 0px;
      height: 0px;
      background: #d3d3d3; 
      opacity:0
    }
    QComboBox:drop-down{
      background-color: #440D0F;
      border: 0px;
      opacity:0;
      border-radius: 0px;
      width: 0px;
      height: 0px;
    }
    QComboBox:hover:!pressed{
      background-color: #5D1A1D;
    }
    QComboBox:pressed{
      background-color: #551812;
    }
    """)
        self.current_year = str(datetime.now().year)
        self.db_wrapper.create_local_table(self.table_name)
        if self.db_wrapper.local_table_is_empty(self.table_name):
            self.db_wrapper.insert_default_values(self.table_name)

        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        big_lifts_units = "kg" if self.db_wrapper.fetch_local_column(
            self.table_name, "units") == "metric" else "lb"

        one_rep_maxes = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "one_rep_maxes"))
        lifts_for_reps = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "lifts_for_reps"))
        self.rm_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name, "rm_history"))

        if not self.current_year in self.rm_history:
            self.add_year_to_rm_history(self.current_year)
            self.rm_history = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "rm_history"))

        if self.units != big_lifts_units:
            units_name = "metric" if self.units == "kg" else "imperial"
            self.db_wrapper.update_table_column(self.table_name, "units",
                                                units_name)
            if units_name == "metric":
                for exercise, weight in one_rep_maxes.items():
                    one_rep_maxes[exercise] = str(pounds_to_kg(weight))
                for exercise, reps_and_weight in lifts_for_reps.items():
                    lifts_for_reps[exercise] = [
                        reps_and_weight[0],
                        str(pounds_to_kg(reps_and_weight[1]))
                    ]

            elif units_name == "imperial":
                for exercise, weight in one_rep_maxes.items():
                    one_rep_maxes[exercise] = str(kg_to_pounds(weight))
                for exercise, reps_and_weight in lifts_for_reps.items():
                    lifts_for_reps[exercise] = [
                        reps_and_weight[0],
                        str(kg_to_pounds(reps_and_weight[1]))
                    ]

            for year in self.rm_history:
                for month in self.rm_history[year]:
                    for exercise_type in list(self.rm_history[year][month]):
                        for exercise in list(
                                self.rm_history[year][month][exercise_type]):
                            for i, weight in enumerate(
                                    self.rm_history[year][month][exercise_type]
                                [exercise]):
                                if units_name == "imperial":
                                    self.rm_history[year][month][
                                        exercise_type][exercise][i] = str(
                                            kg_to_pounds(weight))
                                elif units_name == "metric":
                                    self.rm_history[year][month][
                                        exercise_type][exercise][i] = str(
                                            pounds_to_kg(weight))

            self.db_wrapper.update_table_column(self.table_name,
                                                "one_rep_maxes", one_rep_maxes)
            self.db_wrapper.update_table_column(self.table_name,
                                                "lifts_for_reps",
                                                lifts_for_reps)
            self.convert_lift_history_weight(self.units)

        self.one_RM = [[lift, " ".join([weight, self.units])]
                       for lift, weight in one_rep_maxes.items()]
        self.lifts_reps = [[lift, " ".join(["x".join(weight), self.units])]
                           for lift, weight in lifts_for_reps.items()]

        self.lift_history_window = LiftHistory()
        self.lift_history_window.setGeometry(100, 200, 300, 300)

        self.plists_window = PreferredLifts()
        self.plists_window.change_lifts_signal.connect(
            self.changed_preferred_lifts)

        self.update_1RM_window = Update1RMWindow()
        self.update_1RM_window.change_1RM_lifts_signal.connect(
            self.changed_1RM_lifts)
        self.update_1RM_window.history_signal.connect(
            lambda signal: self.lift_history_window.create_history(signal))
        self.update_1RM_window.update_graph_signal.connect(
            lambda signal: self.refresh_graph(signal))

        self.lifts_for_reps = UpdateLiftsForRepsWindow()
        self.lifts_for_reps.change_lifts_for_reps_signal.connect(
            self.changed_lifts_for_reps)
        self.lifts_for_reps.history_signal.connect(
            lambda signal: self.lift_history_window.create_history(signal))

        self.preferred_lifts = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "preferred_lifts"))
        self.one_rep_maxes = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "one_rep_maxes"))
        self.create_panel()

    def create_panel(self):
        main_panel_grid = QGridLayout()
        main_panel_grid.addLayout(self.description(), 0, 0, 1, 1)
        main_panel_grid.addWidget(self.create_time_graph(), 1, 0, 4, 1)
        main_panel_grid.addLayout(self.create_bottom_layout(), 5, 0, 3, 1)
        main_panel_grid.addLayout(self.create_function_buttons(), 8, 0, 1, 1)
        self.setLayout(main_panel_grid)

    def description(self):
        panel_description = QVBoxLayout()
        desc_font = QFont("Montserrat", 12)
        description_label = QLabel(
            "Keep notes and track progress of your preferred big lifts here.",
            self)
        description_label.setFont(desc_font)
        description_label.setFixedHeight(20)
        panel_description.addWidget(description_label)
        return panel_description

    def create_time_graph(self):
        self.graph_layout = QVBoxLayout()

        graph = OneRMGraphCanvas("Horizontal Press", self.rm_history,
                                 self.current_year, self)

        combobox_layout = QHBoxLayout()
        self.lifts_combobox = QComboBox(self)
        self.lifts_combobox.addItems(list(self.preferred_lifts.values()))
        self.lifts_combobox.currentTextChanged.connect(
            lambda lift: self.change_exercise_graph(lift))

        self.change_year_combobox = QComboBox(self)
        self.change_year_combobox.addItems(list(self.rm_history.keys()))
        self.change_year_combobox.setCurrentText(self.current_year)
        self.change_year_combobox.currentTextChanged.connect(
            lambda year: self.change_graph_year(year))

        combobox_layout.addWidget(self.change_year_combobox)
        combobox_layout.addWidget(self.lifts_combobox)

        toolbar = NavigationToolbar(graph, self)
        toolbar.setStyleSheet("background-color: white;")

        self.graph_layout.addWidget(toolbar)
        self.graph_layout.addWidget(graph)
        self.graph_layout.addLayout(combobox_layout)

        framed_graph = QFrame(self)
        framed_graph.setFrameStyle(QFrame.Box)
        framed_graph.setLineWidth(3)
        framed_graph.setLayout(self.graph_layout)

        return framed_graph

    def create_bottom_layout(self):
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(self.create_one_rep_max())
        bottom_layout.addWidget(self.create_lifts_for_reps())
        return bottom_layout

    def create_one_rep_max(self):
        orm_panel = QVBoxLayout()
        main_label = QLabel("One Rep Max")
        main_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        self.horizontal_press_label_ORM = QLabel(": ".join(self.one_RM[0]))
        self.horizontal_press_label_ORM.setFont(QFont("Ariel", 10))

        self.floor_pull_label_ORM = QLabel(": ".join(self.one_RM[1]))
        self.floor_pull_label_ORM.setFont(QFont("Ariel", 10))

        self.squat_label_ORM = QLabel(": ".join(self.one_RM[2]))
        self.squat_label_ORM.setFont(QFont("Ariel", 10))

        self.vertical_press_label_ORM = QLabel(": ".join(self.one_RM[3]))
        self.vertical_press_label_ORM.setFont(QFont("Ariel", 10))

        orm_buttons = QHBoxLayout()
        update_button = QPushButton("Update")
        update_button.clicked.connect(lambda: self.update_1RM_window.show())
        clear_button = QPushButton("Clear")
        clear_button.clicked.connect(lambda: self.clear_one_rep_maxes())
        orm_buttons.addWidget(update_button)
        orm_buttons.addWidget(clear_button)

        orm_panel.addWidget(main_label)
        orm_panel.addWidget(self.horizontal_press_label_ORM)
        orm_panel.addWidget(self.floor_pull_label_ORM)
        orm_panel.addWidget(self.squat_label_ORM)
        orm_panel.addWidget(self.vertical_press_label_ORM)
        orm_panel.addLayout(orm_buttons)

        orm_panel.setSpacing(5)
        framed_layout = QFrame()
        framed_layout.setObjectName("graphObj")
        framed_layout.setFrameStyle(QFrame.Box)
        framed_layout.setLineWidth(3)
        framed_layout.setStyleSheet("""#graphObj {color: #322d2d;}""")
        framed_layout.setLayout(orm_panel)

        return framed_layout

    def create_lifts_for_reps(self):
        reps_panel = QVBoxLayout()
        main_label = QLabel("Lifts For Reps")
        main_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        self.horizontal_press_label_reps = QLabel(": ".join(
            self.lifts_reps[0]))
        self.horizontal_press_label_reps.setFont(QFont("Ariel", 10))

        self.floor_pull_label_reps = QLabel(": ".join(self.lifts_reps[1]))
        self.floor_pull_label_reps.setFont(QFont("Ariel", 10))

        self.squat_label_reps = QLabel(": ".join(self.lifts_reps[2]))
        self.squat_label_reps.setFont(QFont("Ariel", 10))

        self.vertical_press_label_reps = QLabel(": ".join(self.lifts_reps[3]))
        self.vertical_press_label_reps.setFont(QFont("Ariel", 10))

        reps_buttons = QHBoxLayout()
        update_button = QPushButton("Update")
        update_button.clicked.connect(lambda: self.lifts_for_reps.show())
        clear_button = QPushButton("Clear")
        clear_button.clicked.connect(lambda: self.clear_lifts_for_reps())
        reps_buttons.addWidget(update_button)
        reps_buttons.addWidget(clear_button)

        reps_panel.addWidget(main_label)
        reps_panel.addWidget(self.horizontal_press_label_reps)
        reps_panel.addWidget(self.floor_pull_label_reps)
        reps_panel.addWidget(self.squat_label_reps)
        reps_panel.addWidget(self.vertical_press_label_reps)
        reps_panel.addLayout(reps_buttons)

        framed_layout = QFrame()
        framed_layout.setObjectName("graphObj")
        framed_layout.setFrameStyle(QFrame.Box)
        framed_layout.setLineWidth(3)
        framed_layout.setStyleSheet("""#graphObj {color: #322d2d;}""")
        framed_layout.setLayout(reps_panel)

        return framed_layout

    def create_function_buttons(self):
        buttons_panel = QHBoxLayout()
        lift_history_button = QPushButton()
        lift_history_button.setText("Lift History")
        lift_history_button.clicked.connect(
            lambda: self.lift_history_window.show())
        preferred_lists_button = QPushButton()
        preferred_lists_button.setText("Preferred Lifts")
        preferred_lists_button.clicked.connect(
            lambda: self.plists_window.show())

        buttons_panel.addWidget(lift_history_button)
        buttons_panel.addWidget(preferred_lists_button)
        return buttons_panel

    @pyqtSlot(bool)
    def changed_preferred_lifts(self, changed):
        if changed:
            self.preferred_lifts = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "preferred_lifts"))
            parsed_lifts = list(self.preferred_lifts.values())

            one_RM_labels = [
                self.horizontal_press_label_ORM, self.floor_pull_label_ORM,
                self.squat_label_ORM, self.vertical_press_label_ORM
            ]

            lifts_for_reps_labels = [
                self.horizontal_press_label_reps, self.floor_pull_label_reps,
                self.squat_label_reps, self.vertical_press_label_reps
            ]

            for i, label in enumerate(one_RM_labels):
                label_text = label.text().split(":")
                label_text[0] = parsed_lifts[i]
                label.setText(": ".join(label_text))

            for i, label in enumerate(lifts_for_reps_labels):
                label_text = label.text().split(":")
                label_text[0] = parsed_lifts[i]
                label.setText(": ".join(label_text))

            self.refresh_graph(True)

    @pyqtSlot(bool)
    def changed_1RM_lifts(self, changed):
        if changed:
            fetch_weight = list(
                json.loads(
                    self.db_wrapper.fetch_local_column(
                        self.table_name, "one_rep_maxes")).values())
            self.set_1RM_labels_text(fetch_weight)

    @pyqtSlot(bool)
    def changed_lifts_for_reps(self, changed):
        if changed:
            fetch_reps_and_weight = list(
                json.loads(
                    self.db_wrapper.fetch_local_column(
                        self.table_name, "lifts_for_reps")).values())
            self.set_lifts_for_reps_labels_text(fetch_reps_and_weight)

    def set_lifts_for_reps_labels_text(self, text):
        lifts_for_reps_labels = [
            self.horizontal_press_label_reps, self.floor_pull_label_reps,
            self.squat_label_reps, self.vertical_press_label_reps
        ]

        for i, label in enumerate(lifts_for_reps_labels):
            label_text = label.text().split(": ")
            label_text[1] = " ".join(["x".join(text[i]), self.units])
            label.setText(": ".join(label_text))

    def set_1RM_labels_text(self, text):
        one_RM_labels = [
            self.horizontal_press_label_ORM, self.floor_pull_label_ORM,
            self.squat_label_ORM, self.vertical_press_label_ORM
        ]
        for i, label in enumerate(one_RM_labels):
            label_text = label.text().split(": ")
            label_text[1] = " ".join([text[i], self.units])
            label.setText(": ".join(label_text))

    def clear_one_rep_maxes(self):
        for exercise, value in self.one_rep_maxes.items():
            self.one_rep_maxes[exercise] = "0"
        self.db_wrapper.update_table_column(self.table_name, "one_rep_maxes",
                                            self.one_rep_maxes)
        self.set_1RM_labels_text(list(self.one_rep_maxes.values()))
        self.update_1RM_window.set_line_edit_values()

    def clear_lifts_for_reps(self):
        lifts_for_reps = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "lifts_for_reps"))
        for exercise in lifts_for_reps:
            lifts_for_reps[exercise] = ["0", "0"]
        self.db_wrapper.update_table_column(self.table_name, "lifts_for_reps",
                                            lifts_for_reps)
        self.set_lifts_for_reps_labels_text(list(lifts_for_reps.values()))
        self.lifts_for_reps.set_line_edit_values()

    def replace_graph(self, lift_type):
        new_graph = OneRMGraphCanvas(lift_type, self.rm_history,
                                     self.current_year, self)
        new_toolbar = NavigationToolbar(new_graph, self)
        new_toolbar.setStyleSheet("background-color: white;")

        old_toolbar_reference = self.graph_layout.itemAt(0).widget()
        old_graph_reference = self.graph_layout.itemAt(1).widget()

        self.graph_layout.replaceWidget(old_toolbar_reference, new_toolbar)
        self.graph_layout.replaceWidget(old_graph_reference, new_graph)

        old_toolbar_reference.deleteLater()
        old_graph_reference.deleteLater()

    def change_exercise_graph(self, exercise_name):
        lift_type = None
        for l_type, exercise in self.preferred_lifts.items():
            if exercise == exercise_name: lift_type = l_type
        self.replace_graph(lift_type)

    def change_graph_year(self, year):
        self.current_year = year
        lift_type = None
        for l_type, exercise in self.preferred_lifts.items():
            if exercise == str(self.lifts_combobox.currentText()):
                lift_type = l_type
        self.replace_graph(lift_type)
        self.change_year_combobox.setCurrentText(self.current_year)

    @pyqtSlot(bool)
    def refresh_graph(self, signal):
        if signal:
            self.rm_history = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "rm_history"))
            lift_type = None
            for l_type, exercise in self.preferred_lifts.items():
                if exercise == str(self.lifts_combobox.currentText()):
                    lift_type = l_type
            self.replace_graph(lift_type)

    def convert_lift_history_weight(self, convert_to_units):
        try:
            lift_history = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "lift_history"))
        except TypeError:  # lift history is empty
            return
        if convert_to_units == "kg":
            for lift in lift_history:
                if isinstance(
                        lift[1], list
                ):  # second element of history entry is list, it is lifts_for_reps entry
                    lift[1][1] = str(pounds_to_kg(float(lift[1][1])))
                else:
                    lift[1] = str(pounds_to_kg(float(lift[1])))
        elif convert_to_units == "lb":
            for lift in lift_history:
                if isinstance(lift[1], list):
                    lift[1][1] = str(kg_to_pounds(float(lift[1][1])))
                else:
                    lift[1] = str(kg_to_pounds(float(lift[1])))
        lift_history = json.dumps(lift_history)
        self.db_wrapper.update_table_column(self.table_name,
                                            "lift_history",
                                            lift_history,
                                            convert_lift_history_units=True)

    def add_year_to_rm_history(self, year):
        new_year = {}
        for month in self.db_wrapper.months:
            exercises_dict = {}
            for lift_type in self.preferred_lifts:
                exercises_dict[lift_type] = {
                    self.preferred_lifts[lift_type]: []
                }
            new_year[month] = exercises_dict
        self.rm_history[str(year)] = new_year
        self.rm_history = json.dumps(self.rm_history)
        self.db_wrapper.update_table_column(self.table_name, "rm_history",
                                            self.rm_history)
class CreateWorkoutWindow(QWidget):
  refresh_my_workouts_signal = pyqtSignal(str)
  refresh_after_creating_signal = pyqtSignal(bool)

  def __init__(self, workout_name=None, one_time=False, date=None):
    super().__init__()
    self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
    self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
    self.setWindowModality(Qt.ApplicationModal)
    if workout_name != None:
      self.setWindowTitle("Edit Workout")
    else:
      self.setWindowTitle("Create a New Workout")
    self.db_wrapper = DatabaseWrapper()
    self.table_name = "Workouts"
    self.workout_name = workout_name
    self.one_time = one_time
    self.current_date = date
    self.fetched_my_workouts = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "my_workouts"))
    self.create_panel()

  def create_panel(self):
    layout = QVBoxLayout()
    
    workout_name_layout = QHBoxLayout()
    workout_name_label = QLabel("Workout Name:")
    self.workout_name_edit = QLineEdit()
    workout_name_layout.addWidget(workout_name_label)
    workout_name_layout.addWidget(self.workout_name_edit)
    
    grid_layout = QGridLayout()
    empty = QLabel("")
    name_label = QLabel("Name")
    sets_label = QLabel("Sets")
    reps_label = QLabel("Reps")
    rest_label = QLabel("Rest(Opt.)[min]")
    grid_layout.addWidget(empty, 0, 0)
    grid_layout.addWidget(name_label, 0, 1)
    grid_layout.addWidget(sets_label, 0, 2)
    grid_layout.addWidget(reps_label, 0, 3)
    grid_layout.addWidget(rest_label, 0, 4)
    
    exercise_number = [None] * 10
    self.name_edits = [None] * 10
    self.sets_edits = [None] * 10
    self.reps_edits = [None] * 10
    self.rest_edits = [None] * 10
    
    j = 1
    for i in range(10):
      exercise_number[i] = QLabel("Exercise #"+ str(i+1))
      self.name_edits[i], self.sets_edits[i], self.reps_edits[i], self.rest_edits[i] = QLineEdit(), QLineEdit(), QLineEdit(), QLineEdit()
      self.sets_edits[i].setValidator(QIntValidator())
      self.reps_edits[i].setValidator(QIntValidator())
      self.rest_edits[i].setValidator(QIntValidator())
      grid_layout.addWidget(exercise_number[i], j, 0)
      grid_layout.addWidget(self.name_edits[i], j, 1)
      grid_layout.addWidget(self.sets_edits[i], j, 2)
      grid_layout.addWidget(self.reps_edits[i], j, 3)
      grid_layout.addWidget(self.rest_edits[i], j, 4)
      j += 1
    
    if self.workout_name != None:
      self.workout_name_edit.setText(self.workout_name)
      for i, exercise in enumerate(self.fetched_my_workouts[self.workout_name].keys()):
        self.name_edits[i].setText(exercise)
        self.sets_edits[i].setText(self.fetched_my_workouts[self.workout_name][exercise]["Sets"])
        self.reps_edits[i].setText(self.fetched_my_workouts[self.workout_name][exercise]["Reps"])
        self.rest_edits[i].setText(self.fetched_my_workouts[self.workout_name][exercise]["Rest"])

    buttons_layout = QHBoxLayout()
    save_button = QPushButton("Save")
    save_button.clicked.connect(lambda: self.save_changes())
    cancel_button = QPushButton("Cancel")
    cancel_button.clicked.connect(lambda: self.close())
    buttons_layout.addWidget(save_button)
    if self.workout_name != None:
      delete_button = QPushButton("Delete Workout")
      delete_button.clicked.connect(lambda: self.delete_workout())
      buttons_layout.addWidget(delete_button)
    buttons_layout.addWidget(cancel_button)

    layout.addLayout(workout_name_layout)
    layout.addLayout(grid_layout)
    layout.addLayout(buttons_layout)
    self.setLayout(layout)
  
  def delete_workout(self):
    message_box = QMessageBox()
    message_box.setIcon(QMessageBox.Question)
    message_box.setText("Are you sure you want to delete this workout?")
    message_box.setWindowTitle("Confirm delete") 
    message_box.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
    message_box.buttonClicked.connect(lambda answer: self.delete_workout_confirmed(answer.text()))
    message_box.exec_()

  def delete_workout_confirmed(self, answer):
    if "OK" in answer:
      del self.fetched_my_workouts[self.workout_name]
      self.db_wrapper.update_table_column(self.table_name, "my_workouts", json.dumps(self.fetched_my_workouts))
      self.refresh_my_workouts_signal.emit(self.workout_name)
      self.close()

  def save_changes(self):
    workout_name = self.workout_name_edit.text()
    if workout_name != "":
      new_workout = {}
      for i in range(10):
        exercise_dict = {}
        if self.name_edits[i].text() != "" and self.sets_edits[i].text() != "" and self.reps_edits[i].text() != "":
          exercise_dict["Sets"] = str(self.sets_edits[i].text())
          exercise_dict["Reps"] = str(self.reps_edits[i].text())
          exercise_dict["Rest"] = "N/A" if self.rest_edits[i].text() == "" else str(self.rest_edits[i].text())
          new_workout[self.name_edits[i].text()] = exercise_dict
      if self.one_time == False:
        self.fetched_my_workouts[workout_name] = new_workout
        self.db_wrapper.update_table_column(self.table_name, "my_workouts", json.dumps(self.fetched_my_workouts))
      else:
        workouts = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "workouts"))
        if not self.current_date in workouts:
          workouts[self.current_date] = {"Personal Notes": "", "Workout Name": "None"}
        workouts[self.current_date]["Workout Name"] = workout_name
        workouts[self.current_date]["Exercises"] = new_workout
        self.db_wrapper.update_table_column(self.table_name, "workouts", json.dumps(workouts))
      self.refresh_after_creating_signal.emit(True)
    self.close()
Esempio n. 12
0
class WeightLossEditDialog(QWidget):
    update_label_signal = pyqtSignal(bool)
    update_weight_signal = pyqtSignal(bool)
    update_cardio_notes_signal = pyqtSignal(str)
    update_graph_signal = pyqtSignal(bool)

    def __init__(self, to_edit, old_value, fitness_goal=None, date=None):
        super().__init__()
        assert to_edit in ("Current Weight", "Weight Goal", "Loss Per Week",
                           "Time Spent", "Distance Travelled")
        if to_edit == "Loss Per Week":
            assert fitness_goal != None
            self.fitness_goal = fitness_goal
        elif to_edit == "Current Weight":
            assert date != None
            self.date = date

        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Weight Loss"
        self.to_edit = to_edit
        self.old_value = old_value
        self.current_date = datetime.today().strftime("%d/%m/%Y")
        self.setStyleSheet("""QWidget{
      background-color: #232120;
      color:#c7c7c7;
      font-weight: bold;
      font-family: Montserrat;
      font-size: 16px;
      }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }
    QLineEdit{
      padding: 6px;
      background-color: rgb(33,33,33);
      border: 1px solid;
      border-color: #cdcdcd;
    }""")
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("".join(["Edit ", self.to_edit]))
        self.layout = QVBoxLayout()
        self.layout.addLayout(self.create_layout())
        self.setLayout(self.layout)

    def create_layout(self):
        layout = QVBoxLayout()
        self.line_edit = QLineEdit()

        buttons_layout = QHBoxLayout()
        save_button = QPushButton("Save")
        save_button.clicked.connect(lambda: self.update_to_edit())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close())
        buttons_layout.addWidget(save_button)
        buttons_layout.addWidget(cancel_button)

        if self.to_edit in ("Current Weight", "Weight Goal", "Time Spent",
                            "Distance Travelled"):
            self.line_edit.setValidator(QIntValidator())
        elif self.to_edit == "Loss Per Week":
            self.line_edit.setValidator(QDoubleValidator())
        self.line_edit.setText(str(self.old_value))

        layout.addWidget(self.line_edit)
        layout.addLayout(buttons_layout)

        return layout

    def update_to_edit(self):
        mappings = {
            "Current Weight": "weight",
            "Weight Goal": "goalweight",
            "Loss Per Week": "goalparams"
        }
        if self.to_edit == "Current Weight":
            weight_history = json.loads(
                self.db_wrapper.fetch_local_column(self.table_name,
                                                   "weight_history"))
            weight_history[self.date] = self.line_edit.text()
            self.db_wrapper.update_table_column(self.table_name,
                                                "weight_history",
                                                json.dumps(weight_history))
            self.update_graph_signal.emit(True)
            if self.current_date == self.date:
                self.db_wrapper.update_table_column("Users", "weight",
                                                    self.line_edit.text())
            self.update_weight_signal.emit(True)
        elif self.to_edit == "Weight Goal":
            self.db_wrapper.update_table_column("Users", "goalweight",
                                                self.line_edit.text())
        elif self.to_edit == "Loss Per Week":
            self.db_wrapper.update_table_column(
                "Users", "goalparams",
                json.dumps([self.fitness_goal,
                            self.line_edit.text()]))
        else:
            self.update_cardio_notes_signal.emit(self.line_edit.text())
        self.update_label_signal.emit(True)
        self.close()
Esempio n. 13
0
class SelectWorkout(QWidget):
    refresh_workout_done_signal = pyqtSignal(bool)

    def __init__(self, date):
        super().__init__()
        self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      color:#c7c7c7;
      font-weight: bold;
      font-family: Montserrat;
      font-size: 16px;
      }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }""")
        self.db_wrapper = DatabaseWrapper()
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.table_name = "Workouts"
        self.current_date = date
        self.fetched_my_workouts = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name, "my_workouts"))
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("Select My Workout")
        self.create_panel()

    def create_panel(self):
        layout = QVBoxLayout()
        if len(self.fetched_my_workouts) == 0:
            layout.addWidget(QLabel("My Workouts not found"))
        else:
            groupbox = QGroupBox()
            radio_layout = QVBoxLayout()
            self.radio_buttons = [None] * len(self.fetched_my_workouts.keys())
            for i, workout in enumerate(self.fetched_my_workouts.keys()):
                self.radio_buttons[i] = QRadioButton(workout)
                radio_layout.addWidget(self.radio_buttons[i])
            groupbox.setLayout(radio_layout)
            layout.addWidget(groupbox)

        buttons_layout = QHBoxLayout()
        save_button = QPushButton("Save")
        save_button.clicked.connect(lambda: self.save_workout())
        cancel_button = QPushButton("Cancel")
        cancel_button.clicked.connect(lambda: self.close())
        buttons_layout.addWidget(save_button)
        buttons_layout.addWidget(cancel_button)

        layout.addLayout(buttons_layout)
        self.setLayout(layout)

    def save_workout(self):
        for button in self.radio_buttons:
            if button.isChecked():
                fetched_workouts = json.loads(
                    self.db_wrapper.fetch_local_column(self.table_name,
                                                       "workouts"))
                if not self.current_date in fetched_workouts:
                    fetched_workouts[self.current_date] = {
                        "Personal Notes": "",
                        "Workout Name": "None"
                    }
                fetched_workouts[
                    self.current_date]["Workout Name"] = button.text()
                fetched_workouts[self.current_date][
                    "Exercises"] = self.fetched_my_workouts[button.text()]
                self.db_wrapper.update_table_column(
                    self.table_name, "workouts", json.dumps(fetched_workouts))
                self.refresh_workout_done_signal.emit(True)
                self.close()
Esempio n. 14
0
class WorkoutPlanner(QWidget):
    def __init__(self):
        super().__init__()
        self.setStyleSheet("""
    QWidget{
      color:#c7c7c7;
      font-weight: bold;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: left;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
      border-color: #6C6C6C;
    }""")

        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Workouts"
        self.db_wrapper.create_local_table(self.table_name)
        if self.db_wrapper.local_table_is_empty(self.table_name):
            self.db_wrapper.insert_default_values(self.table_name)
        self.fetched_workouts = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name, "workouts"))
        self.current_date = datetime.today().strftime("%d/%m/%Y")
        if not self.current_date in self.fetched_workouts:
            self.fetched_workouts[self.current_date] = {
                "Personal Notes": "",
                "Workout Name": "None"
            }
            self.db_wrapper.update_table_column(
                self.table_name, "workouts", json.dumps(self.fetched_workouts))
        self.create_panel()

    def create_panel(self):
        self.grid = QGridLayout()
        self.grid.addWidget(self.create_calendar(), 0, 0, 2, 1)
        self.grid.addWidget(self.create_stats(), 0, 1, 2, 1)
        self.grid.addWidget(self.create_left_details(), 2, 0, 2, 1)
        self.grid.addWidget(self.create_right_details(), 2, 1, 2, 1)
        self.setLayout(self.grid)

    def create_calendar(self):
        frame = QFrame()
        frame.setFrameStyle(QFrame.StyledPanel)

        layout = QHBoxLayout()

        self.calendar = QCalendarWidget(self)
        self.calendar.setLocale(QLocale(QLocale.English))
        self.calendar.setFirstDayOfWeek(Qt.DayOfWeek.Monday)
        self.calendar.clicked.connect(lambda: self.show_date())
        layout.addWidget(self.calendar)

        frame.setLayout(layout)

        return frame

    def create_stats(self):
        frame = QFrame()
        frame.setFrameStyle(QFrame.StyledPanel)

        stats_layout = QVBoxLayout()
        stats_label = QLabel("Stats")
        stats_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        number_of_workouts = QLabel(" ".join([
            "Total Number Of Workouts Done:",
            str(len(self.fetched_workouts))
        ]))

        counter_this_month = 0
        for date in self.fetched_workouts:
            if date.split("/")[1] == self.current_date.split("/")[1]:
                counter_this_month += 1

        workouts_done_this_month = QLabel(" ".join(
            ["Workouts Done This Month:",
             str(counter_this_month)]))

        last_workout = list(self.fetched_workouts.keys())[-1]
        for date, workout in reversed(list(self.fetched_workouts.items())):
            if len(workout) > 1:  # found workout that is not todays default
                last_workout = date
                break
        last_workout = QLabel(" ".join(["Last Workout:", last_workout]))

        stats_layout.addWidget(stats_label)
        stats_layout.addWidget(number_of_workouts)
        stats_layout.addWidget(workouts_done_this_month)
        stats_layout.addWidget(last_workout)

        frame.setLayout(stats_layout)

        return frame

    def create_left_details(self):
        frame = QFrame()
        frame.setFrameStyle(QFrame.StyledPanel)

        layout = QVBoxLayout()

        self.day_label = QLabel(self.current_date)
        self.day_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        workout_done_layout = QHBoxLayout()
        self.workout_done_label = QLabel(" ".join([
            "Workout Done:",
            self.fetched_workouts[self.current_date]["Workout Name"]
        ]))
        workout_done_button = QPushButton("Change")
        workout_done_button.clicked.connect(lambda: self.change_workout_done())
        workout_done_layout.addWidget(self.workout_done_label)
        workout_done_layout.addWidget(workout_done_button)

        specific_workout_layout = QHBoxLayout()
        specific_workout_label = QLabel(
            "Create a workout specific for one day: ")
        specific_workout_button = QPushButton("1 Time Workout")
        specific_workout_button.clicked.connect(
            lambda: self.show_1_time_window())
        specific_workout_layout.addWidget(specific_workout_label)
        specific_workout_layout.addWidget(specific_workout_button)

        personal_notes_layout = QVBoxLayout()
        personal_notes_label = QLabel("Personal Notes:")
        self.text_edit = QTextEdit()
        self.text_edit.setStyleSheet("color: black;")
        self.text_edit.setText(
            self.fetched_workouts[self.current_date]["Personal Notes"])
        self.personal_notes_save_button = QPushButton("Save Changes")
        self.personal_notes_save_button.clicked.connect(
            lambda: self.update_personal_notes())
        personal_notes_layout.addWidget(personal_notes_label)
        personal_notes_layout.addWidget(self.text_edit)
        personal_notes_layout.addWidget(self.personal_notes_save_button)

        layout.addWidget(self.day_label)
        layout.addLayout(workout_done_layout)
        layout.addLayout(specific_workout_layout)
        layout.addLayout(personal_notes_layout)
        frame.setLayout(layout)

        return frame

    def create_right_details(self):
        frame = QFrame()
        frame.setFrameStyle(QFrame.StyledPanel)

        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignTop)

        details_label = QLabel("Workout Details")
        details_label.setFont(QFont("Ariel", 18, weight=QFont.Bold))

        self.grid_layout = QGridLayout()
        name_label = QLabel("Exercise Name")
        sets_label = QLabel("Sets")
        reps_label = QLabel("Reps")
        rest_label = QLabel("Rest")

        layout.addWidget(details_label)
        self.grid_layout.addWidget(name_label, 0, 0)
        self.grid_layout.addWidget(sets_label, 0, 1)
        self.grid_layout.addWidget(reps_label, 0, 2)
        self.grid_layout.addWidget(rest_label, 0, 3)

        if "Exercises" in self.fetched_workouts[self.current_date]:
            exercises_count = len(
                self.fetched_workouts[self.current_date]["Exercises"])

            self.number_of_exercises_label = QLabel(" ".join(
                ["Number of Exercises:",
                 str(exercises_count)]))

            set_count = 0

            for exercise in self.fetched_workouts[
                    self.current_date]["Exercises"]:
                set_count += int(self.fetched_workouts[self.current_date]
                                 ["Exercises"][exercise]["Sets"])

            self.total_set_count_label = QLabel(" ".join(
                ["Total Set Count:", str(set_count)]))

            layout.addWidget(self.number_of_exercises_label)
            layout.addWidget(self.total_set_count_label)

            names_labels = [None] * len(
                self.fetched_workouts[self.current_date]["Exercises"].keys())
            sets_labels = [None] * len(
                self.fetched_workouts[self.current_date]["Exercises"].keys())
            reps_labels = [None] * len(
                self.fetched_workouts[self.current_date]["Exercises"].keys())
            rest_labels = [None] * len(
                self.fetched_workouts[self.current_date]["Exercises"].keys())

            j = 1
            for i, exercise in enumerate(self.fetched_workouts[
                    self.current_date]["Exercises"].keys()):
                names_labels[i] = QLabel(exercise)
                sets_labels[i] = QLabel(
                    str(self.fetched_workouts[self.current_date]["Exercises"]
                        [exercise]["Sets"]))
                reps_labels[i] = QLabel(
                    str(self.fetched_workouts[self.current_date]["Exercises"]
                        [exercise]["Reps"]))
                rest_labels[i] = QLabel(
                    str(self.fetched_workouts[self.current_date]["Exercises"]
                        [exercise]["Rest"]))

                self.grid_layout.addWidget(names_labels[i], j, 0)
                self.grid_layout.addWidget(sets_labels[i], j, 1)
                self.grid_layout.addWidget(reps_labels[i], j, 2)
                self.grid_layout.addWidget(rest_labels[i], j, 3)
                j += 1

        layout.addWidget(QLabel(""))
        layout.addLayout(self.grid_layout)
        frame.setLayout(layout)

        return frame

    def show_date(self):
        self.current_date = self.get_calendar_date()
        if not self.current_date in self.fetched_workouts:
            self.fetched_workouts[self.current_date] = {
                "Personal Notes": "",
                "Workout Name": "None"
            }
        self.day_label.setText(self.current_date)
        self.refresh_workout_done(True, True)
        self.text_edit.setText(
            self.fetched_workouts[self.current_date]["Personal Notes"])

    def get_calendar_date(self):
        date = self.calendar.selectedDate()
        day = str(date.day()) if date.day() > 9 else "0" + str(date.day())
        month = str(
            date.month()) if date.month() > 9 else "0" + str(date.month())
        parsed_date = "/".join([day, month, str(date.year())])
        return parsed_date

    def show_1_time_window(self):
        self.create_workout_window = CreateWorkoutWindow(
            one_time=True, date=self.get_calendar_date())
        if self.db_wrapper.connection_exists:
            self.create_workout_window.refresh_after_creating_signal.connect(
                lambda signal: self.refresh_workout_done(signal))
        self.create_workout_window.setGeometry(100, 200, 300, 300)
        self.create_workout_window.show()

    def update_personal_notes(self):
        self.fetched_workouts[self.current_date][
            "Personal Notes"] = self.text_edit.toPlainText()
        self.db_wrapper.update_table_column(self.table_name, "workouts",
                                            json.dumps(self.fetched_workouts))

    def change_workout_done(self):
        self.select_workout_window = SelectWorkout(self.get_calendar_date())
        self.select_workout_window.refresh_workout_done_signal.connect(
            lambda signal: self.refresh_workout_done(signal))
        self.select_workout_window.setGeometry(100, 200, 300, 300)
        self.select_workout_window.show()

    @pyqtSlot(bool)
    def refresh_workout_done(self, signal, date_change=False):
        if signal:
            if not date_change:
                self.fetched_workouts = json.loads(
                    self.db_wrapper.fetch_local_column(self.table_name,
                                                       "workouts"))
            self.workout_done_label.setText(" ".join([
                "Workout Done:",
                self.fetched_workouts[self.current_date]["Workout Name"]
            ]))
            old_right_details_reference = self.grid.itemAt(3).widget()
            new_right_details = self.create_right_details()
            self.grid.replaceWidget(old_right_details_reference,
                                    new_right_details)
            old_right_details_reference.setParent(None)
Esempio n. 15
0
class Update1RMWindow(QWidget):
  change_1RM_lifts_signal = pyqtSignal(bool)
  history_signal = pyqtSignal(bool)
  update_graph_signal = pyqtSignal(bool)

  def __init__(self):
    super().__init__()
    self.db_wrapper = DatabaseWrapper()
    self.table_name = "Compound Exercises"
    self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
    self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
    self.setWindowModality(Qt.ApplicationModal)
    self.current_year = str(datetime.now().year)
    self.units = "kg" if self.db_wrapper.fetch_local_column("Users", "units") == "metric" else "lb"
    self.preferred_lifts = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "preferred_lifts"))
    self.setWindowTitle("Update One Rep Max Lifts")
    self.setLayout(self.create_panel())
    self.set_line_edit_values()

  def create_panel(self):
    form_layout = QFormLayout()

    exercise_label = QLabel("Exercise")
    weight_label = QLabel("Weight")
    
    horizontal_press_label = QLabel(self.preferred_lifts["Horizontal Press"])
    self.horizontal_press_edit = QLineEdit()
    self.horizontal_press_edit.setValidator(QIntValidator())

    units_label = QLabel(self.units)
    hbox = QHBoxLayout()
    hbox.addWidget(self.horizontal_press_edit)
    hbox.addWidget(units_label)

    floor_pull_label = QLabel(self.preferred_lifts["Floor Pull"])
    self.floor_pull_edit = QLineEdit()
    self.floor_pull_edit.setValidator(QIntValidator())
    
    units_label1 = QLabel(self.units)
    hbox1 = QHBoxLayout()
    hbox1.addWidget(self.floor_pull_edit)
    hbox1.addWidget(units_label1)

    squat_label = QLabel(self.preferred_lifts["Squat"])
    self.squat_edit = QLineEdit()
    self.squat_edit.setValidator(QIntValidator())
    
    units_label2 = QLabel(self.units)
    hbox2 = QHBoxLayout()
    hbox2.addWidget(self.squat_edit)
    hbox2.addWidget(units_label2)

    vertical_press_label = QLabel(self.preferred_lifts["Vertical Press"])
    self.vertical_press_edit = QLineEdit()
    self.vertical_press_edit.setValidator(QIntValidator())
    
    units_label3 = QLabel(self.units)
    hbox3 = QHBoxLayout()
    hbox3.addWidget(self.vertical_press_edit)
    hbox3.addWidget(units_label3)
    
    buttons_layout = QHBoxLayout()
    save_button = QPushButton("Save")
    save_button.clicked.connect(lambda: self.save_1RM_lifts())
    cancel_button = QPushButton("Cancel")
    cancel_button.clicked.connect(lambda: self.close_update_1RM())
    buttons_layout.addWidget(save_button)
    buttons_layout.addWidget(cancel_button)
    
    form_layout.addRow(exercise_label, weight_label)
    form_layout.addRow(horizontal_press_label, hbox)
    form_layout.addRow(floor_pull_label, hbox1)
    form_layout.addRow(squat_label, hbox2)
    form_layout.addRow(vertical_press_label, hbox3)
    
    main_layout = QVBoxLayout()
    main_layout.addLayout(form_layout)
    main_layout.addLayout(buttons_layout)
    
    return main_layout
  
  def save_1RM_lifts(self):
    try:
      fetched_rep_maxes = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "one_rep_maxes"))
      exercises = list(fetched_rep_maxes.keys())
      horizontal_press_max = str(float(self.horizontal_press_edit.text()))
      floor_pull_max = str(float(self.floor_pull_edit.text()))
      squat_max = str(float(self.squat_edit.text()))
      vertical_press_max = str(float(self.vertical_press_edit.text()))
      new_maxes = {exercises[0]:horizontal_press_max, exercises[1]:floor_pull_max,
                   exercises[2]:squat_max, exercises[3]:vertical_press_max}
      
      diff = self.lift_difference(new_maxes, fetched_rep_maxes, one_RM=True)
      
      self.db_wrapper.update_table_column(self.table_name, "lift_history", diff) 
      self.history_signal.emit(True)
      
      self.db_wrapper.update_table_column(self.table_name, "one_rep_maxes", new_maxes) 
      self.update_one_rep_maxes_history(diff, self.current_year)
      
      self.update_graph_signal.emit(True)
      self.change_1RM_lifts_signal.emit(True)
      
      self.set_line_edit_values()
      self.close() 
    except ValueError: # user submitted text/empty string
      pass
  
  def close_update_1RM(self):
    self.close()
    self.set_line_edit_values()

  def set_line_edit_values(self):
    one_rep_maxes = list(json.loads(self.db_wrapper.fetch_local_column(self.table_name, "one_rep_maxes")).values())
    self.horizontal_press_edit.setText(one_rep_maxes[0])
    self.floor_pull_edit.setText(one_rep_maxes[1])
    self.squat_edit.setText(one_rep_maxes[2])
    self.vertical_press_edit.setText(one_rep_maxes[3])

  def sort_exercises(self, exercise):
    if exercise in ["Bench Press", "Incline Bench Press"]: return 4
    elif exercise in ["Deadlift", "Sumo Deadlift"]: return 3
    elif exercise in ["Back Squat", "Front Squat"]: return 2
    elif exercise in ["Overhead Press", "Push Press"]: return 1 

  # returns sorted dictionary containing updated lifts
  def lift_difference(self, new_lifts, old_lifts, one_RM=False, lifts_reps=False):
    difference = None
    if one_RM:
      db_lifts = set(": ".join([exercise, weight]) for exercise, weight in old_lifts.items())
      new_lifts = set(": ".join([exercise, weight]) for exercise, weight in new_lifts.items() if not weight == '0.0')
      diff = list(new_lifts.difference(db_lifts)) # local lifts that are not in db
      difference = {exercise.split(": ")[0]:exercise.split(": ")[1] for exercise in diff}
    elif lifts_reps:
      db_lifts = set(":".join([exercise, "x".join(values)]) for exercise, values in old_lifts.items())
      new_lifts = set(":".join([exercise, "x".join(values)]) for exercise, values in new_lifts.items() if not values[1] == '0.0')
      diff = list(new_lifts.difference(db_lifts))
      difference = {exercise.split(":")[0]:exercise.split(":")[1].split("x") for exercise in diff}
    return {key: value for key, value in sorted(difference.items(), key=lambda exercise: self.sort_exercises(exercise[0]))}

  def update_one_rep_maxes_history(self, diff, year):
    rm_history = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "rm_history"))
    default_exercises = {"Horizontal Press": "Bench Press", "Floor Pull": "Deadlift",
                         "Squat": "Back Squat", "Vertical Press": "Overhead Press"}
    secondary_exercises = {"Horizontal Press": "Incline Bench Press", "Floor Pull": "Sumo Deadlift",
                           "Squat": "Front Squat", "Vertical Press": "Push Press"} 
    exercises = {}

    for default in default_exercises:
      if not default in exercises: exercises[default] = []
      exercises[default].append(default_exercises[default])

    for secondary in secondary_exercises:
      exercises[secondary].append(secondary_exercises[secondary])

    now = datetime.now()
    if year not in rm_history:
      rm_history[year] = {}
      for month in self.db_wrapper.months:
        exercises_dict = {}
        for lift_type in default_exercises:
          exercises_dict[lift_type] = {default_exercises[lift_type]:[]}
        for lift_type in secondary_exercises:
          exercises_dict[lift_type][secondary_exercises[lift_type]] = []
        rm_history[year][month] = exercises_dict 
    
    for i, (lift, weight) in enumerate(diff.items()):
      lift_type = None
      for exercise_type in exercises:
        if lift in exercises[exercise_type]: lift_type = exercise_type
      entry = rm_history[year][self.db_wrapper.months[now.month-1]][lift_type]
      if lift not in entry: entry[lift] = []
      entry[lift].append(weight) 
    
    rm_history = json.dumps(rm_history)
    self.db_wrapper.update_table_column(self.table_name, "rm_history", rm_history)
Esempio n. 16
0
class TestBigLifts(unittest.TestCase):
  def setUp(self):
    self.test_class = TestClass("big_lifts", "test.db")
    self.db_wrapper = DatabaseWrapper("test.db")
    
    self.table_name = "Compound Exercises"
    self.test_class.create_test_user()
    self.db_wrapper.create_local_table("Compound Exercises")
    self.db_wrapper.insert_default_values("Compound Exercises")
  
  def tearDown(self):
    self.test_class.delete_test_user()
  
  def test_create_big_lifts_table(self):
    big_lifts_columns = ("email", "one_rep_maxes", "lifts_for_reps",
                         "preferred_lifts", "lift_history",
                         "units", "rm_history")
    columns = self.test_class.fetch_column_names()
    self.assertEqual(big_lifts_columns, columns)
  
  def test_insert_default_values(self):
    default_exercises = ["Bench Press", "Deadlift", "Back Squat", "Overhead Press"]
    one_RM = json.dumps({exercise: "0" for exercise in default_exercises})
    lifts_for_reps = json.dumps({exercise: ["0", "0"] for exercise in default_exercises})
    preferred_lifts = {"Horizontal Press": "Bench Press", "Floor Pull": "Deadlift",
                       "Squat": "Back Squat", "Vertical Press": "Overhead Press"}
    secondary_exercises = {"Horizontal Press": "Incline Bench Press", "Floor Pull": "Sumo Deadlift",
                           "Squat": "Front Squat", "Vertical Press": "Push Press"}
  
    months = ["January", "February", "March", "April", "May", "June", "July",
                  "August", "September", "October", "November", "December"]
    current_year = str(datetime.now().year)
    rm_history = {current_year:{}}
    for month in months:
      exercises_dict = {}
      for lift_type in preferred_lifts:
        exercises_dict[lift_type] = {preferred_lifts[lift_type]:[]}
      for lift_type in secondary_exercises:
        exercises_dict[lift_type][secondary_exercises[lift_type]] = []
      
      rm_history[current_year][month] = exercises_dict

    default_values = {"one_rep_maxes": one_RM, "lifts_for_reps": lifts_for_reps,
                      "preferred_lifts": json.dumps(preferred_lifts), "rm_history": json.dumps(rm_history),
                      "email": self.test_class.test_user["email"], "units": self.test_class.test_user["units"]} 
    
    big_lifts_data = self.test_class.fetch_all_remote_columns()[0]
    
    # big_lifts_data[4] == lift_history
    fetched_email = big_lifts_data[0]
    fetched_one_RM = big_lifts_data[1]
    fetched_lifts_for_reps = big_lifts_data[2]
    fetched_preferred_lifts = big_lifts_data[3]
    fetched_units = big_lifts_data[5]
    fetched_rm_history = big_lifts_data[6]

    fetched_default_values = {"one_rep_maxes": fetched_one_RM, "lifts_for_reps": fetched_lifts_for_reps,
                              "preferred_lifts": fetched_preferred_lifts, "rm_history": fetched_rm_history,
                              "email": fetched_email, "units": fetched_units}

    self.assertDictEqual(fetched_default_values, default_values)
  
  def test_update_units(self):
    new_units = "imperial"
    self.db_wrapper.update_table_column("Users", "units", "imperial")
    self.db_wrapper.update_table_column(self.table_name, "units", "imperial")
    units = self.test_class.fetch_column_from_local_table("units")
    self.assertEqual(new_units, units)
  
  def test_update_1RM_lifts(self):
    new_values = {"Bench Press": "100", "Deadlift": "200",
                  "Back Squat": "300", "Overhead Press": "400"}
    self.db_wrapper.update_table_column(self.table_name, "one_rep_maxes", new_values)
    
    server_1RM = json.loads(self.test_class.fetch_column_from_remote_table("one_rep_maxes"))
    self.assertEqual(new_values, server_1RM)

    local_1RM = json.loads(self.test_class.fetch_column_from_local_table("one_rep_maxes"))
    self.assertEqual(new_values, local_1RM)
  
  def test_update_lifts_for_reps(self):
    new_values = {"Bench Press": ["10", "100"], "Deadlift": ["3", "250"],
                  "Back Squat": ["5", "200"], "Overhead Press": ["1", "100"]}
    self.db_wrapper.update_table_column(self.table_name, "lifts_for_reps", new_values) 
    server_lifts_for_reps = json.loads(self.test_class.fetch_column_from_remote_table("lifts_for_reps"))
    self.assertEqual(new_values, server_lifts_for_reps)
    
    local_lifts_for_reps = json.loads(self.test_class.fetch_column_from_local_table("lifts_for_reps"))
    self.assertEqual(new_values, local_lifts_for_reps)
  
  # case 1: lift history doesn't exist
  def test_update_lift_history(self):
    new_lift_history = {"Bench Press": ["10", "300"],
                        "Deadlift": "100",
                        "Back Squat": "500",
                        "Push Press": ["100", "30"]}
    self.db_wrapper.update_table_column(self.table_name, "lift_history", new_lift_history)
    local_lift_history = json.loads(self.test_class.fetch_column_from_local_table("lift_history"))
    correct_lift_history = [["Bench Press", ["10", "300"], 3],
                            ["Deadlift", "100", 2],
                            ["Back Squat", "500", 1],
                            ["Push Press", ["100", "30"], 0]]
    self.assertEqual(correct_lift_history, local_lift_history)
  
  # case 2: lift history exists
  def test_update_lift_history_2(self):
    lift_history = {"Bench Press": ["10", "300"],
                    "Deadlift": "100",
                    "Back Squat": "500",
                    "Push Press": ["100", "30"]}
    self.db_wrapper.update_table_column(self.table_name, "lift_history", lift_history)
    new_lift_history = {"Incline Bench Press": "300",
                        "Deadlift": ["3", "180"]}
    self.db_wrapper.update_table_column(self.table_name, "lift_history", new_lift_history)
    local_lift_history = json.loads(self.test_class.fetch_column_from_local_table("lift_history"))
    correct_lift_history = [["Incline Bench Press", "300", 5],
                            ["Deadlift", ["3", "180"], 4],
                            ["Bench Press", ["10", "300"], 3],
                            ["Deadlift", "100", 2],
                            ["Back Squat", "500", 1],
                            ["Push Press", ["100", "30"], 0]]
    try: self.assertEqual(correct_lift_history, local_lift_history) # test is passing, assertion fails because of id's
    except AssertionError: pass
  
  def test_update_preferred_lifts(self):
    new_preferred_lifts = {"Horizontal Press": "Incline Bench Press", "Floor Pull": "Deadlift",
                                      "Squat": "Front Squat", "Vertical Press": "Overhead Press"}

    self.db_wrapper.update_table_column(self.table_name, "preferred_lifts", new_preferred_lifts)
    local_preferred_lifts = json.loads(self.test_class.fetch_column_from_local_table("preferred_lifts"))
    self.assertDictEqual(new_preferred_lifts, local_preferred_lifts)
Esempio n. 17
0
class LiftHistory(QScrollArea):
  def __init__(self):
    super().__init__()
    self.db_wrapper = DatabaseWrapper()
    self.table_name = "Compound Exercises"
    self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
    self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
    self.setWindowModality(Qt.ApplicationModal)
    self.units = "kg" if self.db_wrapper.fetch_local_column("Users", "units") == "metric" else "lb"
    self.setWindowTitle("Lift History")
    
    widget = QWidget()
    self.layout = QFormLayout(widget)
    
    self.setWidget(widget)
    self.setWidgetResizable(True)
    self.create_history(True, True)

  @pyqtSlot(bool)
  def create_history(self, create, init_layout=False):
    exercise_label = QLabel("Exercise")
    exercise_label.setAlignment(Qt.AlignCenter)
    delete_label = QLabel("Delete")
    delete_label.setAlignment(Qt.AlignCenter)

    helper_layout = QFormLayout()
    
    helper_layout.addRow(exercise_label, delete_label)

    self.lift_history = self.db_wrapper.fetch_local_column(self.table_name, "lift_history")
    if create and not self.lift_history == None:
      if not init_layout:
        if not self.db_wrapper.connection_exists: return
        self.delete_history()
      lift_history = json.loads(self.lift_history)
      self.labels = [None] * len(lift_history)
      self.delete_buttons = [None] * len(lift_history)

      for i in range(len(lift_history)):
        self.labels[i] = QLabel(self)
        self.delete_buttons[i] = QPushButton("X", self)
      
      for j, exercise in enumerate(lift_history):
        try:
          self.labels[j].setText(": ".join([exercise[0], " ".join([exercise[1], self.units])]))
        except TypeError: # joining lift for reps as 1RM lift 
          self.labels[j].setText(": ".join([exercise[0], " ".join(["x".join(exercise[1]), self.units])]))
        
        self.delete_buttons[j].setProperty("entry_index", exercise[-1])
        self.delete_buttons[j].clicked.connect(partial(self.delete_history_entry_from_layout, j, self.delete_buttons[j].property("entry_index")))
        
        helper_layout.addRow(self.labels[j], self.delete_buttons[j])

    scroll_area = QScrollArea()
    scroll_area.setContentsMargins(3, 3, 3, 3)
    scroll_area.setWidgetResizable(True)
    helper_widget = QWidget()
    helper_widget.setLayout(helper_layout)
    scroll_area.setWidget(helper_widget)
    self.layout.addRow(scroll_area)

    close_button = QPushButton("Close")
    close_button.clicked.connect(lambda:self.close())
    self.layout.addRow(close_button)

  def delete_history(self):
    for i in reversed(range(self.layout.count())):
      self.layout.itemAt(i).widget().setParent(None)
  
  def delete_history_entry_from_layout(self, i, entry_index):
    self.labels[i].setParent(None)
    self.delete_buttons[i].setParent(None)
    history = json.loads(self.db_wrapper.fetch_local_column(self.table_name, "lift_history"))
    lift_history = [lift for lift in history if not lift[-1] == entry_index]
    if len(lift_history) == 0: lift_history = None
    else: lift_history = json.dumps(lift_history)
    self.db_wrapper.update_table_column(self.table_name, "lift_history", lift_history, True)
Esempio n. 18
0
class WeightLossHistory(QScrollArea):
    update_weight_loss_label_signal = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self.db_wrapper = DatabaseWrapper()
        self.table_name = "Weight Loss"
        self.setStyleSheet("""
    QWidget{
      background-color: #232120;
      font-weight: bold;
      color:#c7c7c7;
    }
    QPushButton{
      background-color: rgba(0, 0, 0, 0);
      border: 1px solid;
      font-size: 18px;
      font-weight: bold;
      border-color: #808080;
      min-height: 28px;
      white-space:nowrap;
      text-align: center;
      padding-left: 5%;
      font-family: Montserrat;
    }
    QPushButton:hover:!pressed{
      border: 2px solid;
      border-color: #747474;
    }
    QPushButton:pressed{
      border: 2px solid;
      background-color: #323232;
    }
    """)
        self.units = "kg" if self.db_wrapper.fetch_local_column(
            "Users", "units") == "metric" else "lb"
        self.weight_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "weight_history"))
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle("Weight History")

        widget = QWidget()
        self.layout = QGridLayout(widget)
        self.setWidget(widget)
        self.setWidgetResizable(True)

        self.create_history(True, True)

    @pyqtSlot(bool)
    def create_history(self, create, init_layout=False):
        if create and len(self.weight_history) > 0:
            if not init_layout:
                self.update_weight_loss_label_signal.emit(True)
                self.delete_history()

            helper_layout = QGridLayout()

            date_label = QLabel("Date")
            date_label.setAlignment(Qt.AlignCenter)
            weight_label = QLabel("Weight")
            weight_label.setAlignment(Qt.AlignCenter)

            edit_label = QLabel("Edit")
            edit_label.setAlignment(Qt.AlignCenter)
            delete_label = QLabel("Delete")
            delete_label.setAlignment(Qt.AlignCenter)

            helper_layout.addWidget(date_label, 0, 0)
            helper_layout.addWidget(weight_label, 0, 1)
            helper_layout.addWidget(edit_label, 0, 2)
            helper_layout.addWidget(delete_label, 0, 3)

            self.date_labels = [None] * len(self.weight_history)
            self.weight_labels = [None] * len(self.weight_history)
            self.edit_buttons = [None] * len(self.weight_history)
            self.delete_buttons = [None] * len(self.weight_history)

            for i in range(len(self.weight_history)):
                self.date_labels[i] = QLabel(self)
                self.weight_labels[i] = QLabel(self)
                self.edit_buttons[i] = QPushButton("Edit", self)
                self.delete_buttons[i] = QPushButton("X", self)

            row = 1
            for j, date in enumerate(list(reversed(self.weight_history))):
                self.weight_labels[j].setText(" ".join(
                    [self.weight_history[date], self.units]))
                self.date_labels[j].setText(date)
                self.edit_buttons[j].setProperty("date", date)
                self.edit_buttons[j].clicked.connect(
                    partial(self.edit_weight_dialog, "Current Weight",
                            self.weight_history[date],
                            self.edit_buttons[j].property("date")))
                self.delete_buttons[j].setProperty("date", date)
                self.delete_buttons[j].clicked.connect(
                    partial(self.delete_history_entry_from_layout, j,
                            self.delete_buttons[j].property("date")))

                helper_layout.addWidget(self.date_labels[j], row, 0, 1, 1)
                helper_layout.addWidget(self.weight_labels[j], row, 1, 1, 1)
                helper_layout.addWidget(self.edit_buttons[j], row, 2, 1, 1)
                helper_layout.addWidget(self.delete_buttons[j], row, 3, 1, 1)
                row += 1

        scroll_area = QScrollArea()
        scroll_area.setContentsMargins(3, 3, 3, 3)
        scroll_area.setWidgetResizable(True)
        helper_widget = QWidget()
        helper_widget.setLayout(helper_layout)
        scroll_area.setWidget(helper_widget)
        self.layout.addWidget(scroll_area, 0, 0, 1, 1)

        close_button = QPushButton("Close")
        close_button.clicked.connect(lambda: self.close())
        self.layout.addWidget(close_button, row, 0, 1, 4)

    def edit_weight_dialog(self, to_edit, value, date):
        self.edit_weight_dialog_window = WeightLossEditDialog(to_edit,
                                                              value,
                                                              date=date)
        self.edit_weight_dialog_window.update_weight_signal.connect(
            lambda signal: self.create_history(signal))
        self.edit_weight_dialog_window.show()

    def delete_history(self):
        self.weight_history = json.loads(
            self.db_wrapper.fetch_local_column(self.table_name,
                                               "weight_history"))
        for i in reversed(range(self.layout.count())):
            self.layout.itemAt(i).widget().setParent(None)

    def delete_history_entry_from_layout(self, i, date):
        self.date_labels[i].setParent(None)
        self.weight_labels[i].setParent(None)
        self.edit_buttons[i].setParent(None)
        self.delete_buttons[i].setParent(None)
        if date in self.weight_history: del self.weight_history[date]
        self.db_wrapper.update_table_column(self.table_name, "weight_history",
                                            json.dumps(self.weight_history))