import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QVBoxLayout, QPushButton, QHBoxLayout, QTextEdit, QComboBox
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QIcon
import speech_recognition as sr
import pyaudio

class VoiceRecorderThread(QThread):
    finished = pyqtSignal(str)

    def run(self):
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Listening...")
            audio = r.listen(source)
        
        try:
            text = r.recognize_google(audio)
            self.finished.emit(text)
        except sr.UnknownValueError:
            self.finished.emit("Speech recognition could not understand audio")
        except sr.RequestError as e:
            self.finished.emit(f"Could not request results from speech recognition service; {e}")

class CommandInput(QWidget):
    command_entered = pyqtSignal(str, str)  # Modified to include template

    def __init__(self):
        super().__init__()
        self.initUI()
        self.recording = False
        self.recorder_thread = None

    def initUI(self):
        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint | Qt.Tool)
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        self.setWindowTitle("Command Input")

        layout = QVBoxLayout()

        # Create a horizontal layout for the close button
        top_layout = QHBoxLayout()
        close_button = QPushButton("×")
        close_button.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                border: none;
                color: #4CAF50;
                font-size: 20px;
            }
            QPushButton:hover {
                color: red;
            }
        """)
        close_button.clicked.connect(self.hide)
        top_layout.addStretch(1)
        top_layout.addWidget(close_button)

        layout.addLayout(top_layout)

        # Create a horizontal layout for the input and record button
        input_layout = QHBoxLayout()
        self.lineEdit = QLineEdit()
        self.lineEdit.setPlaceholderText("Enter your command...")
        self.lineEdit.setStyleSheet("""
            QLineEdit {
                background-color: white;
                border: 2px solid #4CAF50;
                border-radius: 10px;
                padding: 5px;
                font-size: 16px;
            }
        """)
        input_layout.addWidget(self.lineEdit)

        self.record_button = QPushButton()
        self.record_button.setIcon(QIcon("mic_icon.png"))  # Make sure to have this icon in your project directory
        self.record_button.clicked.connect(self.toggle_recording)
        input_layout.addWidget(self.record_button)

        layout.addLayout(input_layout)

        # Add template selection dropdown
        self.template_dropdown = QComboBox()
        self.template_dropdown.addItem("No template")
        self.update_template_list()
        layout.addWidget(self.template_dropdown)

        # Add a submit button
        self.submit_button = QPushButton("Submit")
        self.submit_button.clicked.connect(self.submit_command)
        layout.addWidget(self.submit_button)

        self.setLayout(layout)
        self.resize(400, 150)

        # Position the widget above the taskbar
        screen = QApplication.primaryScreen().availableGeometry()
        self.move(screen.width() - self.width() - 20, screen.height() - self.height() - 40)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Return:
            self.submit_command()
        elif event.key() == Qt.Key_Escape:
            self.hide()

    def submit_command(self):
        command = self.lineEdit.text()
        template = self.template_dropdown.currentText()
        if template == "No template":
            template = None
        self.lineEdit.clear()
        self.command_entered.emit(command, template)

    def toggle_recording(self):
        if not self.recording:
            self.start_recording()
        else:
            self.stop_recording()

    def start_recording(self):
        self.recording = True
        self.record_button.setIcon(QIcon("stop_icon.png"))  # Make sure to have this icon
        self.recorder_thread = VoiceRecorderThread()
        self.recorder_thread.finished.connect(self.on_recording_finished)
        self.recorder_thread.start()

    def stop_recording(self):
        self.recording = False
        self.record_button.setIcon(QIcon("mic_icon.png"))
        if self.recorder_thread:
            self.recorder_thread.terminate()

    def on_recording_finished(self, text):
        self.stop_recording()
        self.lineEdit.setText(text)
        self.save_template(text)
        self.update_template_list()

    def save_template(self, text):
        os.makedirs("templates", exist_ok=True)
        template_count = len([f for f in os.listdir("templates") if f.startswith("task") and f.endswith(".txt")])
        filename = f"task{template_count + 1}.txt"
        with open(os.path.join("templates", filename), "w") as f:
            f.write(text)

    def update_template_list(self):
        self.template_dropdown.clear()
        self.template_dropdown.addItem("No template")
        for filename in os.listdir("templates"):
            if filename.startswith("task") and filename.endswith(".txt"):
                self.template_dropdown.addItem(filename)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()

    def setEnabled(self, enabled):
        self.lineEdit.setEnabled(enabled)
        self.record_button.setEnabled(enabled)
        self.template_dropdown.setEnabled(enabled)
        self.submit_button.setEnabled(enabled)

# Usage in main.py:
# from ui import CommandInput
# app = QApplication([])
# command_input = CommandInput()
# command_input.show()
# app.exec_()