import os
import sys
import numpy as np
import sounddevice as sd
from scipy.io import wavfile
from PySide6 import QtWidgets, QtCore
import matplotlib.pyplot as plt
from acycle.util.utiltool import readTxt


class InputDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Audio Settings")
        self.resize(300, 250)

        # Create layout
        layout = QtWidgets.QVBoxLayout()

        # First integer input
        self.input1_label = QtWidgets.QLabel("Repeat Count (a):")
        self.input1 = QtWidgets.QSpinBox()
        self.input1.setRange(1, 1000)  # Set reasonable range
        self.input1.setValue(5)  # Default value
        layout.addWidget(self.input1_label)
        layout.addWidget(self.input1)

        # Second integer input
        self.input2_label = QtWidgets.QLabel("Sampling Rate Factor (b):")
        self.input2 = QtWidgets.QDoubleSpinBox()
        self.input2.setRange(0.1, 8192.0)
        self.input2.setSingleStep(0.1)
        self.input2.setValue(1.0)  # Default value
        layout.addWidget(self.input2_label)
        layout.addWidget(self.input2)

        # Third input - ComboBox for Remove Mean option
        self.input3_label = QtWidgets.QLabel("Remove Mean (1=yes, 0=no):")
        self.input3 = QtWidgets.QComboBox()
        self.input3.addItems(["Yes", "No"])
        self.input3.setCurrentIndex(0)  # Default to "Yes"
        layout.addWidget(self.input3_label)
        layout.addWidget(self.input3)

        # Button layout
        button_layout = QtWidgets.QHBoxLayout()
        self.confirm_button = QtWidgets.QPushButton("Confirm")
        self.cancel_button = QtWidgets.QPushButton("Cancel")
        button_layout.addStretch()
        button_layout.addWidget(self.confirm_button)
        button_layout.addWidget(self.cancel_button)
        layout.addLayout(button_layout)

        # Connect signals to slots
        self.confirm_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)

        self.setLayout(layout)

def d2a(file_name = None):
    # Initialize application
    _,data = readTxt(file_name)

    # Create and display input dialog
    dialog = InputDialog()
    if dialog.exec() == QtWidgets.QDialog.Accepted:
        a = dialog.input1.value()
        b = dialog.input2.value()
        c = 1 if dialog.input3.currentText() == "Yes" else 0  # Convert selection to 1 or 0

        try:
            # Process audio data
            if c == 1:
                y = np.tile(data - np.mean(data), (a, 1))
            else:
                y = np.tile(data, (a, 1))

            # Play audio
            fs = int(b * 8192)
            sd.play(y.flatten(), fs)
            sd.wait()

            # Save as WAV file
            dat_name = os.path.splitext(file_name)[0]
            name1 = f"{dat_name}_rep-{a}-rate-{fs}.wav"
            wavfile.write(name1, fs, y)

            print(f"Audio saved as: {name1}")

            # List current directory files (simulating MATLAB's dir and listbox)
            current_files = os.listdir()
            print("Current directory files:")
            for i, file in enumerate(current_files, 1):
                print(f"{i}. {file}")

        except Exception as e:
            print(f"Error during processing: {e}")
    else:
        print("User canceled input")
    # Exit application
    # sys.exit(0)

if __name__ == "__main__":
    d2a('Example-SvalbardPETM-logFe.txt')