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 Information")
        self.language = langHandel("message")
        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( "postedBy")+f" : {project['user']['displayName']}")
        title_label.setStyleSheet("font-size:15px")
        caption_label = QLabel(self.language.get_value( "datePosting")+f" : {project['create']}")
        caption_label.setStyleSheet("font-size:15px")
        create_time_label = QLabel(self.language.get_value( "messageText")+f" : {project['message']}")
        create_time_label.setStyleSheet("font-size:15px")

        layout.addWidget(title_label)
        layout.addWidget(caption_label)
        layout.addWidget(create_time_label)
        #.setLayoutDirection(Qt.RightToLeft)
        self.setLayout(layout)



class MessageInfo(QWidget):
    def __init__(self):
        super().__init__()
        self.language = langHandel("message")
        self.setWindowTitle("EM Detail Message")
        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.setMessage()

    def setMessage(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/getMessage"
        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(self.data )
                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(3)  # Project Name, Creat Time, Project Status, Detail Button
        self.table.setHorizontalHeaderLabels([self.language.get_value( "sender"),self.language.get_value( "datePosting"), self.language.get_value( "view")])

        for row, item in enumerate(self.data):
            self.table.setItem(row, 0, QTableWidgetItem(item['user']['displayName']))
            self.table.setItem(row, 1, QTableWidgetItem(item['create']))

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

        layout.addWidget(self.table)
        self.setLayout(layout)
        #self.setLayoutDirection(Qt.RightToLeft)

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


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