import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QMessageBox, QVBoxLayout, QWidget, QPushButton, QLabel, QFileDialog

class F1ModManager(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

        # Переменные для хранения выбранных файлов 0 Сохранение Сохрание 
        self.custom_track_data = None
        self.database_xml = None

    def initUI(self):
        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle("F1 2014 Track Mod Installer - Beta 1.0")

        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        layout = QVBoxLayout(central_widget)
        
        # Label для отображения названия трека
        self.track_label = QLabel("F1 2014 Track Mod Installer", self)
        self.track_label.setStyleSheet("font-size: 32px; font-weight: 700; color: #cbcbcb;")
        layout.addWidget(self.track_label)

        label1 = QLabel("1. Upload the .xml file containing your custom database track mod", self)
        layout.addWidget(label1)

        custom_track_button = QPushButton("Import Custom Track Data", self)
        custom_track_button.setStyleSheet("""
            QPushButton {
                width: 220px;
                height: 60px;
                font-size: 16px;
                font-weight: 500;
                background: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgb(50, 50, 70), stop:1 rgb(70, 70, 70));
                color: #fdfdfd;
                border-radius: 10px; 
            }
            QPushButton:hover {
                background: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgb(60, 60, 80), stop:1 rgb(80, 80, 80));
                border-radius: 20px; 
                font-weight: 700;
            }
        """)
        custom_track_button.clicked.connect(self.import_custom_track_data)
        layout.addWidget(custom_track_button)

        label2 = QLabel("2. Upload the original database.xml file \n3. Save the database file as .xml and import it into the Ego Database Editor", self)
        layout.addWidget(label2)

        database_button = QPushButton("Upload your database.xml", self)
        database_button.setStyleSheet("""
            QPushButton {
                width: 220px;
                height: 60px;
                font-size: 16px;
                font-weight: 500;
                background: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgb(50, 50, 70), stop:1 rgb(70, 70, 70));
                color: #fdfdfd;
                border-radius: 10px; 
            }
            QPushButton:hover {
                background: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgb(60, 60, 80), stop:1 rgb(80, 80, 80));
                border-radius: 20px; 
                font-weight: 700;
            }
        """)
        database_button.clicked.connect(self.upload_database_xml)
        layout.addWidget(database_button)

        save_button = QPushButton("Save database file as .xml", self)
        save_button.setStyleSheet("""
            QPushButton {
                width: 220px;
                height: 60px;
                font-size: 16px;
                font-weight: 500;
                background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgb(221, 58, 70), stop:0.5 rgb(243, 29, 59), stop:1 rgb(252, 176, 69));
                color: #fdfdfd;
                border-radius: 10px; 
            }
            QPushButton:hover {
                background: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgb(253, 152, 1), stop:1 rgb(221, 58, 70));
                border-radius: 20px; 
                font-weight: 700;
            }
        """)
        save_button.clicked.connect(self.save_database_xml)
        layout.addWidget(save_button)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')
        helpMenu = menubar.addMenu('Help')

        newAction = QAction('New', self)
        newAction.triggered.connect(self.new_project)
        fileMenu.addAction(newAction)

        exitAction = QAction('Exit', self)
        exitAction.triggered.connect(self.close)
        fileMenu.addAction(exitAction)

        aboutAction = QAction('About', self)
        aboutAction.triggered.connect(self.show_about)
        helpMenu.addAction(aboutAction)

        self.statusBar().showMessage("Ready")

    def new_project(self):
        self.custom_track_data = None
        self.database_xml = None
        self.statusBar().showMessage("New project started")

    def show_about(self):
        QMessageBox.about(self, "About", "Author - AlonsoBeast\nLink to Our Discord Modding Server: https://discord.gg/KXt7NC3Sue")

    def import_custom_track_data(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "Select Custom Track Data File", "", "All Files (*)", options=options)
        if file_name:
            self.custom_track_data = file_name
            self.statusBar().showMessage(f"Imported Custom Track Data: {file_name}")

    def upload_database_xml(self):
        options = QFileDialog.Options()
        file_name, _ = QFileDialog.getOpenFileName(self, "Select Database File", "", "All Files (*)", options=options)
        if file_name:
            self.database_xml = file_name
            self.statusBar().showMessage(f"Uploaded Database File: {file_name}")

    def save_database_xml(self):
        if self.custom_track_data and self.database_xml:
            try:
                # Чтение данных из файлов
                with open(self.custom_track_data, 'r', encoding='utf-8') as custom_file:
                    custom_content = custom_file.read()
                with open(self.database_xml, 'r', encoding='utf-8') as database_file:
                    database_content = database_file.read()

                # Разбиваем дополнительный файл на блоки
                custom_blocks = {
                    'track': self.extract_block(custom_content, 'track'),
                    'track_car_handling': self.extract_block(custom_content, 'track_car_handling'),
                    'track_fuel_distance': self.extract_block(custom_content, 'track_fuel_distance'),
                    'track_model': self.extract_block(custom_content, 'track_model'),
                    'track_difficulties': self.extract_block(custom_content, 'track_difficulties')
                }

                # Теги для вставки
                insertion_tags = {
                    'track': ['<track_calendar>', '<track_fuel_distance>'],
                    'track_car_handling': ['<track_difficulties>', '<track_fuel_distance>'],
                    'track_fuel_distance': ['<track_model>', '<calendar_glyph>', '<id>', '<name_string_id>'],
                    'track_model': ['<track_stat_value>', '<track_stat_value>'],
                    'track_difficulties': ['<track_fuel_distance>', '<track_fuel_distance>']
                }

                # Вставка на основе ключевых точек
                for tag, tags in insertion_tags.items():
                    insertion_point = -1
                    for next_tag in tags:
                        insertion_point = database_content.find(next_tag)
                        if insertion_point != -1:  # Если нашли, прекращаем цикл
                            break

                    if insertion_point != -1 and custom_blocks[tag]:
                        # Проверка на наличие track_difficulties
                        if tag == 'track_difficulties':
                            if '<track_difficulties>' not in database_content:
                                continue  # Пропускаем вставку, если тег отсутствует

                        database_content = (
                            database_content[:insertion_point] +
                            custom_blocks[tag] +
                            "\n" +
                            database_content[insertion_point:]
                        )

                file_name, _ = QFileDialog.getSaveFileName(self, "Save Database File", "", "All Files (*)", options=QFileDialog.Options())
                if file_name:
                    with open(file_name, 'w', encoding='utf-8') as output_file:
                        output_file.write(database_content)
                    self.statusBar().showMessage(f"Database saved successfully: {file_name}")
            except Exception as e:
                self.statusBar().showMessage(f"Error during integration: {str(e)}")
        else:
            self.statusBar().showMessage("Please import both data files before saving.")

    @staticmethod
    def extract_block(content, tag):
        """Извлекает блок XML из содержимого для заданного тега."""
        start_tag = f'<{tag}>'
        end_tag = f'</{tag}>'
        start_index = content.find(start_tag)
        end_index = content.find(end_tag, start_index) + len(end_tag)
        if start_index != -1 and end_index != -1:
            return content[start_index:end_index]
        return ''

app = QApplication(sys.argv)
app.setStyleSheet("""
    QMainWindow {
        background-color: #1e1d2b;
        font-family: 'Roboto', sans-serif;
    }
    QLabel {
        color: #cbcbcb;
        font-size: 16px;
    }
    QPushButton {
        background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ff8a00, stop:1 #e52e71);
        color: #FFFFFF;
        font-size: 16px;
        padding: 10px;
        border-radius: 25px;
    }
    /* Удалено свойство box-shadow */
    QMenuBar, QStatusBar {
        background-color: #272938;
        color: #FFFFFF;
    }
    QMenuBar::item:selected {
        background-color: #3C3C3C;
    }
    QMenu {
        background-color: #272938;
        color: #FFFFFF;
    }
    QMenu::item:selected {
        background-color: #3C3C3C;
    }
    QMessageBox {
        font-size: 12px;
        font-weight: 200;
        background-color: #1D1D1D;
    }
""")

window = F1ModManager()
window.show()
sys.exit(app.exec_())