import sys
from PyQt5.QtWidgets import QComboBox,QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QPushButton, QDialog, QLabel
from PyQt5.QtGui import QIcon
import ctypes
import json
import requests
import urllib3
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import Qt

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

state_project_map = {
    0: "doing",
    1: "Canceled",
    2: "done",
    3: "Waiting to start"
}


class DetailDialog(QDialog):
    def __init__(self, project):
        super().__init__()
        self.setWindowTitle("EM Detail Information")
        user32 = ctypes.windll.user32
        screen_width = user32.GetSystemMetrics(0)
        screen_height = user32.GetSystemMetrics(1)
        left = screen_width - 730
        top = screen_height - 420
        self.setGeometry(left, top, 400, 400)
        self.setWindowIcon(QIcon('ixo.png'))

        layout = QVBoxLayout()

        title_label = QLabel(f"Title: {project['title']}")
        title_label.setStyleSheet("font-size:15px")
        caption_label = QLabel(f"Caption: {project['caption']}")
        caption_label.setStyleSheet("font-size:15px")
        create_time_label = QLabel(f"Create Time: {project['creatTime']}")
        create_time_label.setStyleSheet("font-size:15px")
        edit_time_label = QLabel(f"Edit Time: {project['editData']}")
        edit_time_label.setStyleSheet("font-size:15px;")
        status_label = QLabel(f"Status: {state_project_map[project['stateTask']]}")
        status_label.setStyleSheet("font-size:15px;")

        layout.addWidget(title_label)
        layout.addWidget(caption_label)
        layout.addWidget(create_time_label)
        layout.addWidget(edit_time_label)
        layout.addWidget(status_label)

        self.setLayout(layout)



class TaskInfo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("EM Detail Task")
        user32 = ctypes.windll.user32
        screen_width = user32.GetSystemMetrics(0)
        screen_height = user32.GetSystemMetrics(1)
        left = screen_width - 730
        top = screen_height - 420
        self.setGeometry(left, top, 600, 400)
        self.setWindowIcon(QIcon('ixo.png'))

        self.data = []
        self.setTask(True)

    def setTask(self,onUi):
        with open("data.json", "r", encoding='utf-8') as file:
            data = json.load(file)

        host = "https://" + data.get("host")
        with open("login.json", "r", encoding='utf-8') as file:
            login = json.load(file)

        token = login.get("token")
        url = f"{host}/Frogment/Apis/GetTask"
        payload = {'Token': token, "ip": "", "NameClinets": ""}
        headers = {
            "User-Agent": "Your User Agent",  # در صورت نیاز به استفاده از Bearer Token
            "Content-Type": "application/x-www-form-urlencoded"
        }
        try:
            response = requests.request("POST", url, headers=headers,data=payload, verify=False)
            response.raise_for_status()
            if response.status_code == 200:
                if onUi:
                    self.data.clear()
                self.data = response.json()
                if onUi:
                    self.initUI()
            else:
                print("Failed to Get Task")

        except requests.exceptions.HTTPError:
            print("Failed to Get Task")
        except Exception:
            print("Failed to Get Task")

    def initUI(self):
        layout = QVBoxLayout()
        self.table = QTableWidget()
        self.table.setRowCount(len(self.data))
        self.table.setColumnCount(5)  # Project Name, Creat Time, Project Status, Detail Button
        self.table.setHorizontalHeaderLabels(['Task Title', 'Creat Time', 'Task Status', 'Detail','edit'])

        for row, item in enumerate(self.data):
            self.table.setItem(row, 0, QTableWidgetItem(item['title']))
            self.table.setItem(row, 1, QTableWidgetItem(item['creatTime']))
            self.table.setItem(row, 2, QTableWidgetItem(state_project_map[item['stateTask']]))

            detail_button = QPushButton('Show Details')
            Change_button = QPushButton('Change Status')
            detail_button.clicked.connect(lambda _, r=item: self.show_details(r))
            Change_button.clicked.connect(lambda _, r=item: self.change_Status(r))
            self.table.setCellWidget(row, 3, detail_button)
            self.table.setCellWidget(row, 4, Change_button)

        layout.addWidget(self.table)
        self.setLayout(layout)

    def show_details(self, row_data):
        dialog = DetailDialog(row_data)
        dialog.exec_()

    def change_Status(self, row_data):
        dialog = QDialog(self)
        dialog.setWindowTitle("Change Status")
        dialog.setMinimumSize(300, 100)

        combo_box = QComboBox(dialog)
        combo_box.move(20, 20)

        # Data for Task
        title_label = QLabel("Select Status Task  ")
        title_label.move(400, 30)

        task_model = QStandardItemModel()
        standard_item = QStandardItem("doing")
        standard_item.setData(0, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem("Canceled")
        standard_item.setData(1, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem("done")
        standard_item.setData(2, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem("Waiting to start")
        standard_item.setData(3, Qt.UserRole)
        task_model.appendRow(standard_item)

        combo_box.setModel(task_model)

        confirm_button = QPushButton("Confirm", dialog)
        confirm_button.move(200, 20)
        confirm_button.clicked.connect(dialog.accept)

        dialog.exec_()
        if dialog.result() == QDialog.Accepted:
            selected_task_index = combo_box.currentIndex()
            num_id = combo_box.itemData(selected_task_index, Qt.UserRole)
            with open("data.json", "r", encoding='utf-8') as file:
                data = json.load(file)

            # دریافت فیلد host
            host = "https://" + data.get("host")
            headers = {
                "User-Agent": "Your User Agent",  # در صورت نیاز به استفاده از Bearer Token
                "Content-Type": "application/x-www-form-urlencoded"
            }
            with open("login.json", "r", encoding='utf-8') as file:
                login = json.load(file)

            # دریافت فیلد token
            token = login.get("token")
            url = f"{host}/Frogment/Apis/ChangeStateTask"

            dataActive = {
                'Id': row_data["id"],
                'State': num_id,
                'Token': token
            }

            try:

                # ارسال داده‌ها به سرور
                response = requests.request("POST", url,headers=headers, data=dataActive, verify=False)

                if response.status_code == 200:
                    response_json = response.json()
                    if (response_json["status"] == "200"):
                        title_label.setText("Submitted successfully")
                        self.setTask(False)
                    else:
                        title_label.setText(response_json["results"])


                else:
                    title_label.setText("Error sending, please try again")

            except requests.RequestException as e:
                title_label.setText("Error sending, please try again")

            except Exception as e:
                title_label.setText("Error sending, please try again")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = TaskInfo()
    widget.show()
    sys.exit(app.exec_())
