import sys
import csv
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QTableWidget, QTableWidgetItem, QFileDialog, QMessageBox,QWidget,QVBoxLayout
)
from PySide6.QtCore import Qt
SEPERATOR = ','
from util import utiltool
@utiltool.window_shortcut
class TxtEditor(QWidget):
    def __init__(self, file_path=None):
        super().__init__()
        self.setWindowTitle(file_path if file_path else "TXT Editor")
        self.resize(800, 600)

        # 创建表格控件
        self.table = QTableWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.table)
        self.setLayout(layout)
       
        # 如果通过命令行传入了文件路径，则直接加载
        if file_path:
            self.load_txt(file_path)

    def open_txt(self):
        # 打开文件对话框
        file_path, _ = QFileDialog.getOpenFileName(self, "Open TXT File", "", "TXT Files (*.txt)")
        if file_path:
            self.load_txt(file_path)

    def load_txt(self, file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as txtfile:
                lines = txtfile.readlines()
                headers = lines[0].strip().split(SEPERATOR)  # 假设第一行为表头，列之间用制表符分隔
                self.table.setRowCount(0)
                self.table.setColumnCount(len(headers))
                # self.table.setHorizontalHeaderLabels(headers)

                # 填充数据
                for line in lines[0:]:
                    row_data = line.strip().split(SEPERATOR)  # 按制表符分割
                    row_position = self.table.rowCount()
                    self.table.insertRow(row_position)
                    for column, value in enumerate(row_data):
                        item = QTableWidgetItem(value)
                        self.table.setItem(row_position, column, item)
            self.current_file = file_path
            # QMessageBox.information(self, "Success", f"Loaded {file_path}")
        except Exception as e:
            QMessageBox.critical(self, "Error", f"Failed to load TXT:{e}")

    def save_txt(self):
        if not hasattr(self, 'current_file'):
            QMessageBox.warning(self, "Warning", "No file loaded to save.")
            return
        try:
            with open(self.current_file, 'w', encoding='utf-8') as txtfile:
                # 写入表头
                # headers = [self.table.horizontalHeaderItem(i).text() for i in range(self.table.columnCount())]
                # txtfile.write('\t'.join(headers) + '')
                # 写入数据
                for row in range(self.table.rowCount()):
                    row_data = []
                    for column in range(self.table.columnCount()):
                        item = self.table.item(row, column)
                        row_data.append(item.text() if item else "")
                    txtfile.write('\t'.join(row_data) + '')
            QMessageBox.information(self, "Success", f"Saved {self.current_file}")
        except Exception as e:
            QMessageBox.critical(self, "Error", f"Failed to save TXT:{e}")
    def set_file_path(self,file):
        self.setWindowTitle(file)
        self.load_txt(file)



if __name__ == "__main__":
    app = QApplication(sys.argv)
    file_path = 'Example-SvalbardPETM-logFe.txt'
    if len(sys.argv) > 1:
        file_path = sys.argv[1]  # 从命令行获取文件路径
    editor = TxtEditor(file_path)
    editor.show()
    sys.exit(app.exec_())
