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

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['project']['title']}")
        title_label.setStyleSheet("font-size:15px")
        caption_label = QLabel(f"Caption: {project['project']['caption']}")
        caption_label.setStyleSheet("font-size:15px")
        create_time_label = QLabel(f"Create Time: {project['project']['creatTime']}")
        create_time_label.setStyleSheet("font-size:15px")
        edit_time_label = QLabel(f"Edit Time: {project['project']['editData']}")
        edit_time_label.setStyleSheet("font-size:15px;")
        status_label = QLabel(f"Status: {state_project_map[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.setLayout(layout)



class ProjectInfo(QWidget):
    def __init__(self):
        super().__init__()
        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()

    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()
                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(4)  # Project Name, Creat Time, Project Status, Detail Button
        self.table.setHorizontalHeaderLabels(['Project Name', 'Creat Time', 'Project Status', 'Detail'])

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

            detail_button = QPushButton('Show 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)
    widget = ProjectInfo()
    widget.show()
    sys.exit(app.exec_())
