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
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.setWindowTitle("EM Detail Report")
        self.language = langHandel("report")
        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 - 1000
        self.setGeometry(left, top, 400, 800)
        self.setWindowIcon(QIcon('ixo.png'))

        layout = QVBoxLayout()

        title_label = QLabel(self.language.get_value("details")+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("dateProject")+f" : {project['project']['creatTime']}")
        create_time_label.setStyleSheet("font-size:15px")
        status_label = QLabel(self.language.get_value("statusProject")+f" : {self.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(status_label)

        title_label2 = QLabel(self.language.get_value("titleTask")+f" : {project['tasks']['title']}")
        title_label2.setStyleSheet("font-size:15px")
        caption_label2 = QLabel(self.language.get_value("taskDescription")+f" : {project['tasks']['caption']}")
        caption_label2.setStyleSheet("font-size:15px")
        create_time_label2 = QLabel(self.language.get_value("dateTask")+f": {project['tasks']['creatTime']}")
        create_time_label2.setStyleSheet("font-size:15px")
        status_label2 = QLabel(self.language.get_value("statusTask")+f" : {self.state_project_map[int(project['tasks']['stateTask'])]}")
        status_label2.setStyleSheet("font-size:15px;")

        layout.addWidget(title_label2)
        layout.addWidget(caption_label2)
        layout.addWidget(create_time_label2)
        layout.addWidget(status_label2)

        title_label3 = QLabel(self.language.get_value("sent")+f" : {project['report']}")
        title_label3.setStyleSheet("font-size:15px")

        create_time_label3 = QLabel(self.language.get_value("submissionReport")+f" : {project['create']}")
        create_time_label3.setStyleSheet("font-size:15px")


        layout.addWidget(title_label3)
        layout.addWidget(create_time_label3)
        #self.setLayoutDirection(Qt.RightToLeft)
        self.setLayout(layout)



class MainReportSend(QWidget):
    def __init__(self):
        super().__init__()
        self.language = langHandel("report")
        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 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.setReport()
        #self.setLayoutDirection(Qt.RightToLeft)

    def setReport(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/getMyReport"
        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([self.language.get_value("send"), self.language.get_value("forProject"), self.language.get_value("forTask"), self.language.get_value("details")])

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

            detail_button = QPushButton(self.language.get_value("showDetails"))
            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 = MainReportSend()
    widget.show()
    sys.exit(app.exec_())
