import sys
from PyQt5.QtWidgets import QComboBox, QMessageBox,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
from  langHandel import langHandel

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)



class DetailDialog(QDialog):
    def __init__(self, project):
        super().__init__()
        self.language = langHandel("task")
        self.state_project_map = {
            0: self.language.get_value("item1"),
            1: self.language.get_value("item2"),
            2: self.language.get_value("item3"),
            3: self.language.get_value("item4"),
            4: self.language.get_value("item1"),
            5: self.language.get_value("item5"),
        }
        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(self.language.get_value("taskTitle")+f" : {project['title']}")
        title_label.setStyleSheet("font-size:15px")
        caption_label = QLabel(self.language.get_value("taskDescription")+f" : {project['caption']}")
        caption_label.setStyleSheet("font-size:15px")
        create_time_label = QLabel(self.language.get_value("creation")+f" : {project['creatTime']}")
        create_time_label.setStyleSheet("font-size:15px")
        edit_time_label = QLabel(self.language.get_value("editing")+f" : {project['editData']}")
        edit_time_label.setStyleSheet("font-size:15px;")
        status_label = QLabel(self.language.get_value("status")+f" : {str(self.state_project_map[int(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.setLayoutDirection(Qt.RightToLeft)
        self.setLayout(layout)



class TaskInfo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("EM Detail Task")
        self.language = langHandel("task")
        self.state_project_map = {
            0: self.language.get_value("item1"),
            1: self.language.get_value("item2"),
            2: self.language.get_value("item3"),
            3: self.language.get_value("item4"),
            4:self.language.get_value("item1"),
            5: self.language.get_value("item5"),
        }
        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)
        #self.setLayoutDirection(Qt.RightToLeft)
    def show_Succ(self, title, message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.exec_()
    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:
                    if len(self.data) > 0:
                        self.initUI()
                    else:
                        self.show_Succ("attention", "There is no task defined for you")

            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([self.language.get_value("taskTitle"), self.language.get_value("creation"), self.language.get_value("status"), self.language.get_value("details"),self.language.get_value("changeStatus")])

        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( str(self.state_project_map[int(item['stateTask'])])) )

            detail_button = QPushButton(self.language.get_value("details"))
            Change_button = QPushButton(self.language.get_value("changeStatus"))
            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(self.language.get_value("changeStatus"))
        dialog.setMinimumSize(300, 100)

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

        # Data for Task
        title_label = QLabel(self.language.get_value("taskSelectStatus"))
        title_label.move(400, 30)

        task_model = QStandardItemModel()
        standard_item = QStandardItem(self.language.get_value("item1"))
        standard_item.setData(0, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem(self.language.get_value("item2"))
        standard_item.setData(1, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem(self.language.get_value("item3"))
        standard_item.setData(2, Qt.UserRole)
        task_model.appendRow(standard_item)

        standard_item = QStandardItem(self.language.get_value("item4"))
        standard_item.setData(3, Qt.UserRole)
        task_model.appendRow(standard_item)

        combo_box.setModel(task_model)

        confirm_button = QPushButton(self.language.get_value("confirmation"), 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(self.language.get_value("successfullySending"))
                        self.setTask(False)
                    else:
                        title_label.setText(response_json["results"])


                else:
                    title_label.setText(self.language.get_value("errorSending"))

            except requests.RequestException as e:
                title_label.setText(self.language.get_value("errorSending"))

            except Exception as e:
                title_label.setText(self.language.get_value("errorSending"))


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