class ReturnOnlineWidget(QWidget):
    dataUpdated = pyqtSignal()  # Define a signal to notify when data is updated

    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

    def set_font_size(self, font_size):
        font = self.table_widget.font()
        font.setPointSize(font_size)
        self.table_widget.setFont(font)
        header_font = self.table_widget.horizontalHeader().font()
        header_font.setPointSize(font_size)
        self.table_widget.horizontalHeader().setFont(header_font)

    def initUI(self):
        layout = QVBoxLayout(self)

        # Create filter controls
        self.start_date_edit = QDateEdit(self)
        self.start_date_edit.setDate(QDate.currentDate())
        self.start_date_edit.setCalendarPopup(True)
        self.start_date_edit.setDisplayFormat("yyyy-MM-dd")
        self.start_date_edit.dateChanged.connect(self.load_data)
        self.start_date_edit.setFixedWidth(120)  # Set fixed width
        self.start_date_edit.setLocale(english_locale)

        self.end_date_edit = QDateEdit(self)
        self.end_date_edit.setDate(QDate.currentDate())
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.setDisplayFormat("yyyy-MM-dd")
        self.end_date_edit.dateChanged.connect(self.load_data)
        self.end_date_edit.setFixedWidth(120)  # Set fixed width
        self.end_date_edit.setLocale(english_locale)

        self.status_filter = QComboBox(self)
        self.status_filter.addItems(['All', 'WAN down', 'Server down'])
        self.status_filter.currentTextChanged.connect(self.load_data)

        self.duration_edit = QLineEdit(self)
        self.duration_edit.setPlaceholderText(">= Minutes")
        self.duration_edit.textChanged.connect(self.load_data)  
        self.duration_edit.setValidator(QIntValidator(0, 999999, self))

        self.hostname_edit = QLineEdit(self)
        self.hostname_edit.setPlaceholderText("Hostname (All)")
        self.hostname_edit.textChanged.connect(self.load_data)

        self.export_button = QPushButton("Export to CSV", self)
        self.export_button.clicked.connect(self.export_to_csv)
        self.export_button.setFixedWidth(120)  # Set fixed width

        # Layout for filter controls
        filter_layout = QHBoxLayout()
        filter_layout.addWidget(QLabel("Start Date:", self))
        filter_layout.addWidget(self.start_date_edit)
        filter_layout.addWidget(QLabel("End Date:", self))
        filter_layout.addWidget(self.end_date_edit)
        filter_layout.addWidget(QLabel("Status:", self))
        filter_layout.addWidget(self.status_filter)
        filter_layout.addWidget(QLabel("Duration:", self))
        filter_layout.addWidget(self.duration_edit)        
        filter_layout.addWidget(QLabel("Hostname:", self))
        filter_layout.addWidget(self.hostname_edit)
        filter_layout.addWidget(self.export_button)
        layout.addLayout(filter_layout)

        # Status bar
        self.status_bar = QStatusBar(self)
        layout.addWidget(self.status_bar)

        # Create the table widget
        self.table_widget = QTableWidget(self)
        self.table_widget.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Set up table columns and headers
        self.table_widget.setColumnCount(7)
        self.table_widget.setHorizontalHeaderLabels(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])

        # Set resize modes for the table columns
        header = self.table_widget.horizontalHeader()
        #header.setSectionResizeMode(QHeaderView.ResizeToContents)
        header.setStretchLastSection(True)  # Makes the 'Comment' column stretch
        
        # Optionally, adjust resize modes for specific columns
        # header.setSectionResizeMode(0, QHeaderView.ResizeToContents)  # 'Hostname'
        # header.setSectionResizeMode(1, QHeaderView.ResizeToContents)  # 'Storename'
        # header.setSectionResizeMode(2, QHeaderView.Stretch)           # 'Start Offline'
        # header.setSectionResizeMode(3, QHeaderView.Stretch)           # 'End Offline'
        # header.setSectionResizeMode(4, QHeaderView.ResizeToContents)  # 'Duration'
        # header.setSectionResizeMode(5, QHeaderView.ResizeToContents)  # 'Status'
        # header.setSectionResizeMode(6, QHeaderView.Stretch)           # 'Comment'
        
        # Adjust fonts
        font = QFont()
        font.setPointSize(12)
        self.table_widget.setFont(font)
        header.setFont(font)

        # Add table to layout
        layout.addWidget(self.table_widget)
        self.setLayout(layout)

        # Connect data updated signal
        self.dataUpdated.connect(self.load_data)

        # Initial data load
        self.load_data()

    def convert_to_seconds(self, duration):
        try:
            if duration.isdigit():
                return int(duration) * 60  # Convert minutes to seconds
            
            parts = duration.split(':')
            if len(parts) == 3:
                hours, minutes, seconds = map(int, parts)
                return hours * 3600 + minutes * 60 + seconds
            elif len(parts) == 2:  # Handle mm:ss format if needed
                minutes, seconds = map(int, parts)
                return minutes * 60 + seconds
            elif len(parts) == 1:  # Handle ss format if needed
                return int(parts[0])
        except ValueError:
            return None

    def load_data(self):
        folder_path = 'history_log'
        lock_path = 'history_log.lock'
        temp_file_path = 'history_log_temp.txt'
        lock = FileLock(lock_path)

        def is_older_than_180_days(date_str):
            date_format = "%Y-%m-%d"
            try:
                date_obj = datetime.strptime(date_str, date_format)
                return date_obj < datetime.now() - timedelta(days=180)
            except ValueError:
                return True

        try:
            with lock.acquire(timeout=5):  # Wait up to 5 seconds for the lock
                files_to_process = []
                for filename in os.listdir(folder_path):
                    # Exclude history_all.txt from processing
                    if filename.endswith(".txt") and filename != 'history_all.txt' and is_older_than_180_days(filename[:10]):
                        files_to_process.append(os.path.join(folder_path, filename))

                lines = []
                for file_path in files_to_process:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        lines.extend(file.readlines())

                lines_before_cleanup = len(lines)
                lines_after_cleanup = 0
                removed_dates = set()
                with open(temp_file_path, 'w', encoding='utf-8') as temp_file:
                    for line in lines:
                        parts = line.strip().split('|')
                        if len(parts) >= 11:
                            end_offline_date_str = parts[6]  # parts[6] is online_date in 'YYYY-MM-DD' format
                            if is_older_than_180_days(end_offline_date_str):
                                removed_dates.add(end_offline_date_str)
                            else:
                                temp_file.write(line)
                                lines_after_cleanup += 1

                del lines  # Remove reference to lines
                if os.path.exists(temp_file_path):
                    try:
                        os.replace(temp_file_path, os.path.join(folder_path, 'history_all.txt'))
                    except Exception as e:
                        print(f"Error during file replacement: {e}")
                        return
                else:
                    print(f"Temporary file {temp_file_path} does not exist.")
                    return

            # Retrieve user inputs for filtering
            start_date = self.start_date_edit.date().toPyDate()  # Returns a datetime.date object
            end_date = self.end_date_edit.date().toPyDate()      # Returns a datetime.date object
            status_filter = self.status_filter.currentText()
            hostname_filter = self.hostname_edit.text().strip().lower()

            # Parse the duration filter
            user_input_duration = self.duration_edit.text().strip()
            if user_input_duration.isdigit():
                duration_filter = self.convert_to_seconds(user_input_duration)
            else:
                duration_filter = None  # If invalid, don't filter on duration

            rows = []
            with open(os.path.join(folder_path, 'history_all.txt'), 'r', encoding='utf-8') as file:
                for line in file:
                    parts = line.strip().split('|')
                    if len(parts) >= 11:
                        # Parse end_offline_date_str into a datetime.date object
                        try:
                            end_offline_date_str = parts[6]  # online_date
                            end_offline_date = datetime.strptime(end_offline_date_str, '%Y-%m-%d').date()
                        except ValueError:
                            continue  # Skip this line if date can't be parsed

                        # Check if the end_offline_date is within the selected date range
                        if start_date <= end_offline_date <= end_date:
                            # Apply status filter
                            if status_filter == 'All' or parts[9] == status_filter:
                                # Apply hostname filter
                                hostname = parts[2]
                                if hostname_filter == "" or hostname_filter.lower() in hostname.lower():
                                    # Convert duration from the file to seconds for comparison
                                    duration_str = parts[8]
                                    duration = self.convert_to_seconds(duration_str)
                                    if duration_filter is None or (duration is not None and duration >= duration_filter):
                                        start_offline = f"{parts[4]} {parts[5]}"  # start_date and start_time_str
                                        end_offline = f"{parts[6]} {parts[7]}"    # online_date and online_time_str
                                        rows.append([hostname, parts[3], start_offline, end_offline, duration_str, parts[9], parts[10]])

            rows.reverse()  # To show latest entries first

            # Set up table widget
            self.table_widget.setRowCount(len(rows))
            self.table_widget.setColumnCount(7)
            self.table_widget.setHorizontalHeaderLabels(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])
            for row_idx, (hostname, storename, start_offline, end_offline, duration, status, comment) in enumerate(rows):
                self.table_widget.setItem(row_idx, 0, QTableWidgetItem(hostname))
                self.table_widget.setItem(row_idx, 1, QTableWidgetItem(storename))
                self.table_widget.setItem(row_idx, 2, QTableWidgetItem(start_offline))
                self.table_widget.setItem(row_idx, 3, QTableWidgetItem(end_offline))
                self.table_widget.setItem(row_idx, 4, QTableWidgetItem(duration))
                self.table_widget.setItem(row_idx, 5, QTableWidgetItem(status))
                self.table_widget.setItem(row_idx, 6, QTableWidgetItem(comment))
            self.table_widget.verticalHeader().setVisible(False)
            # Update status bar
            total_count = len(rows)
            wan_down_count = sum(1 for row in rows if row[5] == 'WAN down')
            server_down_count = sum(1 for row in rows if row[5] == 'Server down')
            self.status_bar.showMessage(f"Total: {total_count} | WAN down: {wan_down_count} | Server down: {server_down_count}")

        except Timeout:
            print("Failed to acquire file lock")
        except Exception as e:
            print(f"An error occurred: {e}")

    def resizeEvent(self, event):
        super().resizeEvent(event)
        table_width = self.table_widget.width()
        scrollbar_width = 20
        col_percentages = [0.13, 0.31, 0.20, 0.20, 0.10, 0.13, 0.13]
        column_widths = [table_width * p for p in col_percentages]
        total_column_width = sum(column_widths)
        if total_column_width > table_width:
            scale_factor = (table_width - scrollbar_width) / total_column_width
            column_widths = [width * scale_factor for width in column_widths]
        min_last_col_width = 40
        column_widths[-1] = max(column_widths[-1], min_last_col_width)
        for i, width in enumerate(column_widths):
            self.table_widget.setColumnWidth(i, int(width))
        #self.adjust_row_heights()

    def adjust_row_heights(self):
        num_rows = self.table_widget.rowCount()
        self.table_widget.resizeRowsToContents()
        for row in range(num_rows):
            current_height = self.table_widget.rowHeight(row)
            new_height = int(current_height * 1.1)
            self.table_widget.setRowHeight(row, new_height)

    def export_to_csv(self):
        start_date_str = self.start_date_edit.date().toString("yyyy-MM-dd")
        end_date_str = self.end_date_edit.date().toString("yyyy-MM-dd")
        default_filename = f"history_online_{start_date_str}-{end_date_str}.csv"
        file_path, _ = QFileDialog.getSaveFileName(self, "Save CSV File", default_filename, "CSV Files (*.csv)")
        if not file_path:
            return
        if not file_path.endswith(".csv"):
            file_path += ".csv"
        lock_path = 'history_online.lock'
        lock = FileLock(lock_path)
        try:
            with lock.acquire(timeout=10):  # Wait up to 10 seconds for the lock
                with open(file_path, 'w', newline='', encoding='utf-8-sig') as file:
                    writer = csv.writer(file)
                    writer.writerow(['Hostname', 'Storename', 'Start Offline', 'End Offline', 'Duration', 'Status', 'Comment'])
                    for row_idx in range(self.table_widget.rowCount()):
                        row_data = [self.table_widget.item(row_idx, col_idx).text() for col_idx in range(self.table_widget.columnCount())]
                        writer.writerow(row_data)

                print(f"Data exported to {file_path}")
        except Timeout:
            print("Failed to acquire file lock")


make more start and end time for filter data