from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout, QFileDialog, QComboBox, QCheckBox
import sys
# sys.path.append("C:/Users/iuliia/recoUI/serv")
from jsonSelectionWindow import JsonSelectionWindow
from reconsrtuctionApp import ReconstructionApp


class StartApp(QWidget):

    def __init__(self):
        super().__init__()
        # print("TUT")
        self.path_np_data_json = None
        self.path_raw_data = None
        self.path_seq_json = None
        self.path_order_json = None
        self.reconstruction_app = None

        # print("Инициализация окна...")
        self.initUI()
        # print("Окно инициализировано.")

    def initUI(self):

        self.setWindowTitle('Реконструкция')

        layout = QVBoxLayout()

        self.digit_label = QLabel("Выберите (2d или 3d)")
        layout.addWidget(self.digit_label)
        self.digit_input = QComboBox(self)
        self.digit_input.addItems(['2d', '3d'])
        self.digit_input.currentTextChanged.connect(self.update_sequence_options)
        layout.addWidget(self.digit_input)

        self.sequence_label = QLabel("Имя последовательности")
        layout.addWidget(self.sequence_label)
        self.sequence_input = QComboBox(self)
        layout.addWidget(self.sequence_input)

        self.update_sequence_options(self.digit_input.currentText())

        # print(self.sequence_input.currentText(),self.digit_input.currentText())

        self.mat_file_button = QPushButton("Загрузить .mat файл", self)
        self.mat_file_button.clicked.connect(self.load_mat_file)
        layout.addWidget(self.mat_file_button)

        self.mat_file_label = QLabel("Файл .mat не выбран", self)
        layout.addWidget(self.mat_file_label)

        self.json_file_button = QPushButton("Загрузить .json файл", self)
        self.json_file_button.clicked.connect(self.load_json_file)
        layout.addWidget(self.json_file_button)

        self.json_file_label = QLabel("Файл .json не выбран", self)
        layout.addWidget(self.json_file_label)


        ####################################################

        self.open_order_json = QPushButton("Открыть окно выбора JSON", self)
        self.open_order_json.clicked.connect(self.open_json_selection_window)
        layout.addWidget(self.open_order_json)

        # print(self.sequence_input.currentText(),self.digit_input.currentText())
        # self.reconstruction_app = ReconstructionApp(self.sequence_input.currentText(), self.digit_input.currentText())
        # self.path_order_json = self.json_window.path_order_json

        self.phase_shift_checkbox = QCheckBox("Сдвиг по фазе (on/off)", self)
        self.phase_shift_checkbox.setChecked(False)  # По умолчанию отключен
        layout.addWidget(self.phase_shift_checkbox)


        self.start_reco = QPushButton("Начать реконструкцию", self)
        self.start_reco.clicked.connect(self.init_reconstruction)

        layout.addWidget(self.start_reco)


        self.setGeometry(300, 300, 600, 500)
        self.setLayout(layout)


    def update_sequence_options(self, dimension):
        self.sequence_input.clear()

        if dimension == '2d':
            self.sequence_input.addItems([
                'linear_decart',
                'nonlinear_decart(tse)',
                'linear_epi',
                'radial_propeller',
                'linear_decat_readout'
            ])
        elif dimension == '3d':
            self.sequence_input.addItems([
                'linear_decart',
                'nonlinear_decart(tse)'
            ])

    def load_mat_file(self):
        mat_file, _ = QFileDialog.getOpenFileName(self, "Выбрать .mat файл", "", "MAT Files (*.mat)")
        if mat_file:
            self.mat_file_label.setText(f"Загружен .mat файл: {mat_file}")
        else:
            self.mat_file_label.setText("Файл .mat не выбран")

        self.path_raw_data = mat_file

    def load_json_file(self):
        json_file, _ = QFileDialog.getOpenFileName(self, "Выбрать .json файл", "", "JSON Files (*.json)")
        if json_file:
            self.json_file_label.setText(f"Загружен .json файл: {json_file}")
        else:
            self.json_file_label.setText("Файл .json не выбран")

        self.path_np_data_json = json_file

    def open_json_selection_window(self):
        self.json_window = JsonSelectionWindow(
            self.path_np_data_json, self.path_raw_data,
            self.sequence_input.currentText(), self.digit_input.currentText())

        self.path_order_json = self.json_window.path_order_json
        # print(self.path_order_json)
        self.json_window.show()
        self.json_window.closeEvent = lambda event: self.update_order_json_path()
        # print(f"Изначальный путь JSON порядка: {self.path_order_json}")

    def update_order_json_path(self):
        self.path_order_json = self.json_window.path_order_json
        # print(f"Путь к JSON файлу порядка после выбора: {self.path_order_json}")

    # def start_reconstruction(self):

    def init_reconstruction(self):
        if self.phase_shift_checkbox.isChecked():
            # print("Флажок установлен: включён сдвиг по фазе.")
            # Добавьте действия, если флажок установлен
            phase_shift_enabled = True
        else:
            # print("Флажок не установлен: сдвиг по фазе выключен.")
            # Добавьте действия, если флажок не установлен
            phase_shift_enabled = False

        self.reconstruction_app = ReconstructionApp(
            self.sequence_input.currentText(),
            self.digit_input.currentText(),
            phase_shift_enabled
        )
        self.reconstruction_app.start_reconstruction(
            self.path_raw_data, self.path_np_data_json, self.path_order_json
        )





