import sys
from PyQt5.QtWidgets import QApplication, QMessageBox, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QPushButton, QDialog, QLabel
from PyQt5.QtGui import QIcon
import ctypes
import json
import requests
import urllib3
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("project")
        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'))
        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")
        }
        layout = QVBoxLayout()

        title_label = QLabel(self.language.get_value( "projectTitle") +f" : {project['project']['title']}")
        title_label.setStyleSheet("font-size:15px")
        caption_label = QLabel(self.language.get_value( "projectDescription")+f" : {project['project']['caption']}")
        caption_label.setStyleSheet("font-size:15px")
        create_time_label = QLabel(self.language.get_value( "creation") + f" : {project['project']['creatTime']}")
        create_time_label.setStyleSheet("font-size:15px")
        edit_time_label = QLabel(self.language.get_value( "editing") +f" : {project['project']['editData']}")
        edit_time_label.setStyleSheet("font-size:15px;")
        status_label = QLabel(self.language.get_value( "status") +f" : {state_project_map[int(project['project']['stateProject'])]}")
        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 ProjectInfo(QWidget):
    def __init__(self):
        super().__init__()
        self.language = langHandel("project")
        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")
        }
        self.setWindowTitle("EM Detail Project")
        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, 500, 350)
        self.setWindowIcon(QIcon('ixo.png'))

        self.data = []
        self.setProject()
        #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 setProject(self):
        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/GetProject"
        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:

                self.data = response.json()
                print(response.json())
                if len(self.data) > 0:
                    self.initUI()
                else:
                    self.show_Succ(self.language.get_value( "attention"),self.language.get_value( "noProject"))
            else:
                print("Failed to Get Task")

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

    def initUI(self):
        layout = QVBoxLayout()
        if len(self.data)>0:
            self.table = QTableWidget()
            self.table.setRowCount(len(self.data))
            self.table.setColumnCount(4)  # Project Name, Creat Time, Project Status, Detail Button
            self.table.setHorizontalHeaderLabels([self.language.get_value( "projectTitle"), self.language.get_value( "creation"), self.language.get_value( "status"), self.language.get_value( "details")])

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

                detail_button = QPushButton(self.language.get_value( "details"))
                detail_button.clicked.connect(lambda _, r=item: self.show_details(r))
                self.table.setCellWidget(row, 3, detail_button)

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

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


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