from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QListWidget, QListWidgetItem
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt
from job_item import JobItem
from database import add_job_to_db, get_jobs_from_db, update_job_in_db, delete_job_from_db

class JobListWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_jobs_from_db()

    def setup_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)

        job_info_widget = QWidget()
        job_info_layout = QVBoxLayout()
        job_info_widget.setLayout(job_info_layout)

        name_layout = QHBoxLayout()
        name_label = QLabel("Job Name:")
        name_label.setFixedSize(150, 35)
        name_label.setObjectName('jobset')
        name_label.setAlignment(Qt.AlignCenter)
        name_layout.addWidget(name_label)
        self.job_name_edit = QLineEdit()
        name_layout.addWidget(self.job_name_edit)

        folder1_layout = QHBoxLayout()
        folder1_label = QLabel("Folder 1:")
        folder1_label.setFixedSize(150, 35)
        folder1_label.setObjectName('jobset')
        folder1_label.setAlignment(Qt.AlignCenter)
        folder1_layout.addWidget(folder1_label)
        self.folder1_edit = QLineEdit()
        folder1_layout.addWidget(self.folder1_edit)

        folder2_layout = QHBoxLayout()
        folder2_label = QLabel("Folder 2:")
        folder2_label.setFixedSize(150, 35)
        folder2_label.setObjectName('jobset')
        folder2_label.setAlignment(Qt.AlignCenter)
        folder2_layout.addWidget(folder2_label)
        self.folder2_edit = QLineEdit()
        folder2_layout.addWidget(self.folder2_edit)

        interval_layout = QHBoxLayout()
        interval_label = QLabel("Interval:")
        interval_label.setFixedSize(150, 35)
        interval_label.setObjectName('jobset')
        interval_label.setAlignment(Qt.AlignCenter)
        interval_layout.addWidget(interval_label)
        self.interval_edit = QLineEdit()
        interval_layout.addWidget(self.interval_edit)

        buttons_layout = QHBoxLayout()
        self.new_button = QPushButton("New")
        self.new_button.clicked.connect(self.new_job)
        buttons_layout.addWidget(self.new_button)

        self.add_apply_button = QPushButton("Add")
        self.add_apply_button.clicked.connect(self.add_job)
        buttons_layout.addWidget(self.add_apply_button)

        self.apply_button = QPushButton("Apply")
        self.apply_button.clicked.connect(self.apply_job)
        buttons_layout.addWidget(self.apply_button)

        job_info_layout.addLayout(name_layout)
        job_info_layout.addLayout(folder1_layout)
        job_info_layout.addLayout(folder2_layout)
        job_info_layout.addLayout(interval_layout)
        job_info_layout.addLayout(buttons_layout)

        layout.addWidget(job_info_widget)

        self.job_list = QListWidget()
        self.job_list.itemClicked.connect(self.show_job_info)
        layout.addWidget(self.job_list)

    def new_job(self):
        self.job_name_edit.clear()
        self.folder1_edit.clear()
        self.folder2_edit.clear()
        self.interval_edit.clear()
        self.window().add_log('Clicked \'New Job\' !', QColor('yellow'), QColor('green'))

    def add_job(self):
        name = self.job_name_edit.text()
        folder1 = self.folder1_edit.text()
        folder2 = self.folder2_edit.text()
        interval = self.interval_edit.text()

        if name and folder1 and folder2 and interval:
            # Check if job name already exists
            if name == 'jobs' or name == 'logs' or name == 'sqlite_sequence':
                self.window().add_log(f"Job with name '{name}' can not create.", QColor('white'), QColor('red'))
                return
            if any(self.job_list.itemWidget(self.job_list.item(i)).name == name for i in range(self.job_list.count())):
                self.window().add_log(f"Job with name '{name}' already exists.", QColor('white'), QColor('red'))
                return

            job_item = JobItem(name, folder1, folder2, int(interval))
            list_item = QListWidgetItem(self.job_list)
            list_item.setSizeHint(job_item.sizeHint())
            self.job_list.addItem(list_item)
            self.job_list.setItemWidget(list_item, job_item)
            self.job_list.setCurrentItem(list_item)
            job_item.delete_button.clicked.connect(lambda checked, item=list_item: self.delete_job(item))
            
            add_job_to_db(name, folder1, folder2, int(interval))
            self.window().add_log(f'Clicked \'Add Job\' - ({job_item.name})  !', QColor('yellow'), QColor('green'))

    def delete_job(self, list_item):
        job_item = self.job_list.itemWidget(list_item)
        if job_item.thread.is_running:
            job_item.thread.stop()

        self.job_list.takeItem(self.job_list.row(list_item))
        delete_job_from_db(job_item.name)
        self.window().add_log(f'Clicked \'delete Job\' - ({job_item.name}) !', QColor('red'), QColor('green'))

    def show_job_info(self, item):
        job_item = self.job_list.itemWidget(item)
        self.job_name_edit.setText(job_item.name)
        self.folder1_edit.setText(job_item.folder1)
        self.folder2_edit.setText(job_item.folder2)
        self.interval_edit.setText(str(job_item.interval))

    def apply_job(self):
        self.selected_item = self.job_list.selectedItems()[0]
        if self.selected_item:
            job_item = self.job_list.itemWidget(self.selected_item)
            old_name = job_item.name

            new_name = self.job_name_edit.text()
            folder1 = self.folder1_edit.text()
            folder2 = self.folder2_edit.text()
            interval = self.interval_edit.text()

            if new_name and folder1 and folder2 and interval:
                # Check if new job name already exists in other jobs
                item_cnt = self.job_list.count()
                if old_name != new_name and any(self.job_list.itemWidget(self.job_list.item(i)).name == new_name for i in range(item_cnt)):
                    self.window().add_log(f"Job with name '{old_name}' already exists.", QColor('white'), QColor('red'))
                    return

                # Update the database
                update_job_in_db(old_name, new_name, folder1, folder2, int(interval))

                # Update the job item
                # job_item.name = new_name
                # job_item.folder1 = folder1
                # job_item.folder2 = folder2
                # job_item.interval = int(interval)
                # job_item.name_label.setText(new_name)
                job_item = JobItem(new_name, folder1, folder2, int(interval))
                job_item.delete_button.clicked.connect(lambda checked, item=self.selected_item: self.delete_job(item))
                self.job_list.setItemWidget(self.selected_item, job_item)

                self.window().add_log(f'Clicked \'Apply Job\'  - ({job_item.name}) !', QColor('yellow'), QColor('green'))

    def load_jobs_from_db(self):
        jobs = get_jobs_from_db()
        for job in jobs:
            job_item = JobItem(job['name'], job['folder1'], job['folder2'], job['interval'])
            list_item = QListWidgetItem(self.job_list)
            list_item.setSizeHint(job_item.sizeHint())
            self.job_list.addItem(list_item)
            self.job_list.setItemWidget(list_item, job_item)

            job_item.delete_button.clicked.connect(lambda checked, item=list_item: self.delete_job(item))
            

