Esempio n. 1
0
class Popup(QDialog):
    def __init__(self, schedule: Schedule, parent=None, edit_data=None):
        super(Popup, self).__init__(parent)
        self.schedule = schedule
        self.event_name, self.data = edit_data if edit_data is not None else (
            None, None)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.setWindowTitle("Add New Scheduled Notes" if edit_data is None else
                            "Edit {} Details".format(self.event_name))

        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.form_layout = QFormLayout()
        self.form_layout.setContentsMargins(0, 0, 0,
                                            self.form_layout.verticalSpacing())
        self.form_layout_widget = QWidget()
        self.form_layout_widget.setLayout(self.form_layout)

        #The amount of fields in the form that come before the block section (name, #blocks, start, end date, color)
        self.rows_before_blocks = 3

        self.event_type = QPushButton()
        event_type_menu = QMenu()
        event_type_menu.addAction("Class")
        event_type_menu.addSection("Event")
        event_type_menu.addAction("One Time Event")
        event_type_menu.addAction("Recurring Event")
        event_type_menu.addAction("One Time Class Event")
        for action in event_type_menu.actions():
            if not action.isSeparator():
                action.triggered.connect(
                    lambda state, x=action.text(): self.set_type(x))
        self.event_type.setMenu(event_type_menu)
        self.form_layout.addRow("Type:", self.event_type)

        #Class Title
        self.name_edit = QLineEdit()
        self.form_layout.addRow("Name:", self.name_edit)
        #Color
        self.color_picker = QColorDialog()
        self.color_button = QPushButton("Pick Color")
        self.color_button.clicked.connect(self.color_picker.open)
        self.color_picker.currentColorChanged.connect(self.update_color)
        self.form_layout.addRow("Color Code:", self.color_button)

        # Initialize widgets to be added later
        self.start_date_model = DateTimePickerSeriesModel(self)
        self.class_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")
        self.event_start_date = DateTimePickerSeries(self.start_date_model,
                                                     "MMM d yyyy")

        self.end_date_model = DateTimePickerSeriesModel(self)
        self.class_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")
        self.event_end_date = DateTimePickerSeries(self.end_date_model,
                                                   "MMM d yyyy")

        self.event_date_model = DateTimePickerSeriesModel(self)
        self.class_event_date = DateTimePickerSeries(self.event_date_model,
                                                     "MMM d yyyy hh:mm:AP")
        self.event_date = DateTimePickerSeries(self.event_date_model,
                                               "MMM d yyyy hh:mm:AP")

        # Blocks
        self.blocks = 1
        self.spin_box = QSpinBox()
        self.spin_box.setValue(1)
        self.spin_box.setMinimum(1)
        self.spin_box.setMaximum(7)
        self.spin_box.valueChanged.connect(self.update_blocks)

        self.class_picker = QPushButton()
        class_picker_menu = QMenu()
        for class_name in self.schedule.schedule.keys():
            if self.schedule.schedule[class_name]["type"] != "class":
                continue
            class_action = QAction(class_name, parent=class_picker_menu)
            class_action.triggered.connect(lambda state, x=class_action.text():
                                           self.class_picker.setText(x))
            class_picker_menu.addAction(class_action)
        class_picker_menu.aboutToShow.connect(
            lambda: class_picker_menu.setMinimumWidth(self.class_picker.width(
            )))
        self.class_picker.setMenu(class_picker_menu)

        self.stack = QStackedWidget()
        self.stack.setContentsMargins(0, 0, 0, 0)

        class_layout = QFormLayout()
        class_layout.setContentsMargins(0, 0, 0,
                                        class_layout.verticalSpacing())
        class_layout.addRow("Start Date:", self.class_start_date)
        class_layout.addRow("End Date:", self.class_end_date)
        class_layout.addRow("Weekly Blocks:", self.spin_box)
        class_layout.addRow("Block Time:", ClassTimePicker())
        self.class_options = QWidget()
        self.class_options.setSizePolicy(QSizePolicy.Ignored,
                                         QSizePolicy.Ignored)
        self.class_options.setLayout(class_layout)

        recurring_event_layout = QFormLayout()
        recurring_event_layout.setContentsMargins(
            0, 0, 0, recurring_event_layout.verticalSpacing())
        recurring_event_layout.addRow("Start Date:", self.event_start_date)
        recurring_event_layout.addRow("End Date:", self.event_end_date)
        self.recurring_event_time_picker = ClassTimePicker()
        recurring_event_layout.addRow("Event Time:",
                                      self.recurring_event_time_picker)
        self.recurring_event_options = QWidget()
        self.recurring_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                   QSizePolicy.Ignored)
        self.recurring_event_options.setLayout(recurring_event_layout)

        one_time_event_layout = QFormLayout()
        one_time_event_layout.setContentsMargins(
            0, 0, 0, one_time_event_layout.verticalSpacing())
        one_time_event_layout.addRow("Event Date:", self.event_date)
        self.one_time_event_options = QWidget()
        self.one_time_event_options.setSizePolicy(QSizePolicy.Ignored,
                                                  QSizePolicy.Ignored)
        self.one_time_event_options.setLayout(one_time_event_layout)

        class_event_layout = QFormLayout()
        class_event_layout.setContentsMargins(
            0, 0, 0, class_event_layout.verticalSpacing())
        class_event_layout.addRow("Class:", self.class_picker)
        class_event_layout.addRow("Event Date:", self.class_event_date)
        self.class_event_options = QWidget()
        self.class_event_options.setSizePolicy(QSizePolicy.Ignored,
                                               QSizePolicy.Ignored)
        self.class_event_options.setLayout(class_event_layout)

        self.stack.addWidget(self.class_event_options)
        self.stack.addWidget(self.one_time_event_options)
        self.stack.addWidget(self.recurring_event_options)
        self.stack.addWidget(self.class_options)

        if self.data is None:
            self.set_type("Class")

        self.layout.addWidget(self.form_layout_widget)
        self.layout.addWidget(self.stack)
        self.setLayout(self.layout)
        self.show_buttons()

        #Update Values if self.data is defined
        if self.data is not None:
            event_type = self.data["type"]
            self.set_type(camel_case(event_type))
            # noinspection PyTypeChecker
            class_layout: QFormLayout = self.stack.currentWidget().layout()
            self.name_edit.setText(self.event_name)
            self.name_edit.setDisabled(True)
            self.color_picker.setCurrentColor(to_qcolor(self.data["color"]))
            if event_type in ["class", "recurring event"]:
                self.start_date_model.content = QDateTime(
                    to_qdate(self.data["start"]))
                self.end_date_model.content = QDateTime(
                    to_qdate(self.data["end"]))
            if event_type == "class":
                blocks = self.data["blocks"]
                self.update_blocks(len(blocks))
                for i, row in enumerate(
                        range(self.rows_before_blocks,
                              class_layout.rowCount())):
                    block = blocks[i]
                    # noinspection PyTypeChecker
                    block_widget: ClassTimePicker = class_layout.itemAt(
                        row, QFormLayout.FieldRole).widget()
                    block_widget.set_time(to_qtime(block["time"]))
                    block_widget.set_day(block["day"])
            if event_type == "recurring event":
                self.recurring_event_time_picker.set_day(self.data["day"])
                self.recurring_event_time_picker.set_time(
                    to_qtime(self.data["time"]))
            if event_type in ["one time event", "one time class event"]:
                date_time = QDateTime()
                date_time.setDate(to_qdate(self.data["date"]))
                date_time.setTime(to_qtime(self.data["time"]))
                self.event_date_model.content = date_time
            if event_type == "one time class event":
                self.class_picker.setText(self.data["class_name"])

    def show_buttons(self):
        save_button = QDialogButtonBox.Save if self.data is None else QDialogButtonBox.Apply
        cancel_button = QDialogButtonBox.Cancel
        buttonBox = QDialogButtonBox(Qt.Horizontal)
        buttonBox.addButton(save_button).clicked.connect(self.accept)
        buttonBox.addButton(cancel_button).clicked.connect(self.reject)
        if self.data is not None:
            delete_button = buttonBox.addButton(QDialogButtonBox.Discard)
            delete_button.setText("Delete")
            delete_button.clicked.connect(self.delete_event)
        self.layout.addWidget(buttonBox)

    def set_type(self, event_type: str):
        if self.event_type.text() == event_type:
            return
        self.event_type.setText(event_type)
        self.stack.currentWidget().setSizePolicy(QSizePolicy.Ignored,
                                                 QSizePolicy.Ignored)
        if event_type == "Class":
            self.class_options.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Expanding)
            self.class_options.adjustSize()
            self.stack.setCurrentWidget(self.class_options)
        elif event_type == "Recurring Event":
            self.recurring_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                       QSizePolicy.Expanding)
            self.recurring_event_options.adjustSize()
            self.stack.setCurrentWidget(self.recurring_event_options)
        elif event_type == "One Time Event":
            self.one_time_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                      QSizePolicy.Expanding)
            self.one_time_event_options.adjustSize()
            self.stack.setCurrentWidget(self.one_time_event_options)
        elif event_type == "One Time Class Event":
            self.class_event_options.setSizePolicy(QSizePolicy.Expanding,
                                                   QSizePolicy.Expanding)
            self.class_event_options.adjustSize()
            self.stack.setCurrentWidget(self.class_event_options)
        self.stack.adjustSize()
        max_width = 0
        for i in range(self.form_layout.rowCount()):
            widget = self.form_layout.itemAt(i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        # noinspection PyTypeChecker
        current_widget_layout: QFormLayout = self.stack.currentWidget().layout(
        )
        for i in range(current_widget_layout.rowCount()):
            widget = current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget()
            widget.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
            widget.adjustSize()
            max_width = max(widget.size().width(), max_width)
        for i in range(self.form_layout.rowCount()):
            self.form_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        for i in range(current_widget_layout.rowCount()):
            current_widget_layout.itemAt(
                i, QFormLayout.LabelRole).widget().setMinimumWidth(max_width)
        self.adjustSize()

    def update_color(self):
        self.color_button.setStyleSheet(
            "background-color: rgb({},{},{})".format(
                self.color_picker.currentColor().red(),
                self.color_picker.currentColor().green(),
                self.color_picker.currentColor().blue()))

    def update_blocks(self, value):
        if self.spin_box.value() != value:
            self.spin_box.setValue(value)
            return
        if self.blocks == value:
            return
        old_blocks = self.blocks
        self.blocks = value
        class_options_layout: QFormLayout = self.class_options.layout()
        if self.blocks > old_blocks:
            #Change label of block 1
            if old_blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block 1 Time:")
            for i in range(1, self.blocks - old_blocks + 1):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(offset,
                                                     QFormLayout.FieldRole)
                label = class_options_layout.itemAt(offset,
                                                    QFormLayout.LabelRole)
                if widget is not None and label is not None:
                    widget = widget.widget()
                    label = label.widget()
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
                    label.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
                    widget.adjustSize()
                    label.adjustSize()
                    widget.show()
                    label.show()
                else:
                    picker = ClassTimePicker()
                    picker.sizePolicy().setRetainSizeWhenHidden(False)
                    class_options_layout.addRow(
                        "Block {} Time:".format(old_blocks + i), picker)
        elif self.blocks < old_blocks:
            if self.blocks == 1:
                class_options_layout.itemAt(
                    self.rows_before_blocks,
                    QFormLayout.LabelRole).widget().setText("Block Time:")
            for i in range(old_blocks - self.blocks):
                offset = self.rows_before_blocks + old_blocks + i - 1
                widget = class_options_layout.itemAt(
                    offset, QFormLayout.FieldRole).widget()
                label = class_options_layout.itemAt(
                    offset, QFormLayout.LabelRole).widget()
                widget.hide()
                label.hide()
                widget.adjustSize()
                label.adjustSize()
                self.class_options.adjustSize()
                self.stack.adjustSize()
                self.adjustSize()

        # self.class_options.adjustSize()
        # self.stack.adjustSize()
        # self.adjustSize()

    def get_name(self):
        return self.name_edit.text()

    def get_data(self):
        event_type = self.event_type.text()
        data = {
            "type": event_type.lower(),
            "name": self.get_name(),
            "color": {
                "r": self.color_picker.currentColor().red(),
                "g": self.color_picker.currentColor().green(),
                "b": self.color_picker.currentColor().blue(),
            }
        }
        if event_type == "Class":
            block_data = []
            # noinspection PyTypeChecker
            class_layout: QFormLayout = self.stack.currentWidget().layout()
            for row in range(self.rows_before_blocks, class_layout.rowCount()):
                # noinspection PyTypeChecker
                block_widget: ClassTimePicker = class_layout.itemAt(
                    row, QFormLayout.FieldRole).widget()
                if block_widget.isHidden():
                    continue
                time = block_widget.get_time()
                block_data.append({
                    "day": block_widget.day_picker.get_day(),
                    "time": {
                        "hour": time.hour(),
                        "minute": time.minute()
                    }
                })
            data["blocks"] = block_data
        if event_type in ["Class", "Recurring Event"]:
            start_date = self.start_date_model.content.date()
            data["start"] = {
                "day": start_date.day(),
                "month": start_date.month(),
                "year": start_date.year()
            }
            end_date = self.end_date_model.content.date()
            data["end"] = {
                "day": end_date.day(),
                "month": end_date.month(),
                "year": end_date.year()
            }
        if event_type == "Recurring Event":
            data["day"] = self.recurring_event_time_picker.day_picker.get_day()
            time = self.recurring_event_time_picker.get_time()
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        if event_type == "One Time Class Event":
            data["class_name"] = self.class_picker.text()
        if event_type in ["One Time Event", "One Time Class Event"]:
            date_time = self.event_date_model.content
            date = date_time.date()
            time = date_time.time()
            data["date"] = {
                "day": date.day(),
                "month": date.month(),
                "year": date.year(),
            }
            data["time"] = {"hour": time.hour(), "minute": time.minute()}
        return data

    def delete_event(self):
        error = QMessageBox()
        error.setText("Are you sure you would like to delete this event?")
        error.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel)
        result = error.exec_()
        if result == QMessageBox.Yes:
            self.schedule.delete_event(self.event_name)
            self.reject()

    def accept(self):
        event_type = self.event_type.text()
        if event_type == "":
            error = QMessageBox()
            error.setText("Please select a type for the event.")
            error.exec_()
            self.event_type.setFocus()
            return
        # Check Name
        if len(self.get_name()) == 0:
            error = QMessageBox()
            error.setText("Please enter a name for the event.")
            error.exec_()
            self.name_edit.setFocus()
            return
        if event_type in ["Class", "Recurring Event"]:
            # Check Start/End Date
            start_date = self.start_date_model.content.date()
            end_date = self.end_date_model.content.date()
            if start_date >= end_date:
                error = QMessageBox()
                error.setText("End date cannot {} start date.".format(
                    "be equal to" if start_date ==
                    end_date else "come before"))
                error.exec_()
                if event_type == "Class":
                    self.class_end_date.setFocus()
                else:
                    self.event_end_date.setFocus()
                return
            if event_type == "Class":
                # Check Blocks
                # noinspection PyTypeChecker
                class_layout: QFormLayout = self.stack.currentWidget().layout()
                for row in range(self.rows_before_blocks,
                                 class_layout.rowCount()):
                    block_widget = class_layout.itemAt(
                        row, QFormLayout.FieldRole).widget()
                    if block_widget.isHidden():
                        continue
                    # Make sure a day is selected for each block
                    if not block_widget.is_valid():
                        block_name = "the class block" if self.blocks == 1 else str.lower(
                            class_layout.itemAt(row, QFormLayout.LabelRole).
                            widget().text()).replace(" time:", "")
                        error = QMessageBox()
                        error.setText(
                            "Please select a valid day for {}.".format(
                                block_name))
                        error.exec_()
                        return
                    # Check for duplicate blocks
                    for other in range(self.rows_before_blocks,
                                       class_layout.rowCount() - 1):
                        if row == other:
                            continue
                        other_block_widget = class_layout.itemAt(
                            other, QFormLayout.FieldRole).widget()
                        same_time = block_widget.get_time(
                        ) == other_block_widget.get_time()
                        same_day = block_widget.day_picker.get_day(
                        ) == other_block_widget.day_picker.get_day()
                        if same_time and same_day:
                            error = QMessageBox()
                            error.setText(
                                "Block {} and {} cannot have the same day and time."
                                .format(row - self.rows_before_blocks + 1,
                                        other - self.rows_before_blocks + 1))
                            error.exec_()
                            return
            if event_type == "Recurring Event":
                # Make sure a day is selected
                if not self.recurring_event_time_picker.is_valid():
                    error = QMessageBox()
                    error.setText("Please select a valid day for this event.")
                    error.exec_()
                    self.recurring_event_time_picker.setFocus()
                    return
        if event_type == "One Time Class Event":
            # Check Class
            if len(self.class_picker.text()) == 0:
                error = QMessageBox()
                error.setText("Please select a class for this event.")
                error.exec_()
                self.class_picker.setFocus()
                return
        # Valid name
        if self.get_name() in self.schedule.schedule.keys():
            if self.data is None:
                error = QMessageBox()
                error.setText(
                    "An event with this name already exists, would you like to overwrite it?"
                )
                error.setStandardButtons(error.Apply | error.Cancel)
                result = error.exec_()
                if result == error.Apply:
                    to_overwrite = self.schedule.schedule[self.get_name()]
                    if to_overwrite["type"] == "class":
                        if self.event_type.text() == "One Time Class Event":
                            if self.class_picker.text() == self.get_name():
                                error = QMessageBox()
                                error.setText(
                                    "Cannot overwrite a class with a one time class event for that class.\n"
                                    "Please select a different class.")
                                error.setStandardButtons(QMessageBox.Close)
                                error.exec_()
                                return
                    self.schedule.edit_event(self.get_data())
                    self.reject()
                elif result == error.Cancel:
                    self.name_edit.setFocus()
                    return
            self.schedule.edit_event(self.get_data())
            self.reject()
        super(Popup, self).accept()

    def reject(self):
        super(Popup, self).reject()