import sys
import base64
import json
from PyQt5.QtWidgets import QTextEdit,QSplitter, QLineEdit, QFrame, QApplication, QSizePolicy, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QComboBox, QMessageBox, QAction, QDialog
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt
from qt_material import apply_stylesheet
import arabic_reshaper
from bidi.algorithm import get_display
import ctypes
import requests
from MainDashbord import MainDashboard as dashboard
import socket
class MainActivation(QMainWindow):
    def __init__(self):
        super().__init__()
        user32 = ctypes.windll.user32
        screen_width = user32.GetSystemMetrics(0)
        screen_height = user32.GetSystemMetrics(1)
        left = screen_width-430
        top = screen_height  -250
        self.setWindowTitle("EM")
        self.setGeometry( left, top, 400, 200)
        self.setWindowIcon(QIcon('ixo.png'))

        # تنظیمات ویجت‌ها
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout()
        self.central_widget.setLayout(self.layout)

        self.label = QLabel("Enter the activation link")
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setFont(QFont("DejaVu Sans", 22))
        self.layout.addWidget(self.label)

        self.input_text = QLineEdit()
        self.input_text.setAlignment(Qt.AlignCenter)
        self.input_text.setPlaceholderText("Activation link")
        self.input_text.setFont(QFont("DejaVu Sans", 12))
        self.layout.addWidget(self.input_text)

        # ایجاد یک QHBoxLayout برای دکمه‌ها
        self.button_layout = QHBoxLayout()

        self.button = QPushButton("Activate")
        self.button.clicked.connect(self.process_link)
        self.button.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.button.setFixedWidth(self.width() * 0.8)  # تنظیم عرض به 80%
        self.button_layout.addWidget(self.button)

        self.buttonHelp = QPushButton("Help")
        self.buttonHelp.clicked.connect(self.show_help)
        self.buttonHelp.setStyleSheet("border: 2px solid orange; color:orange;")  # تنظیم رنگ حاشیه به نارنجی
        self.buttonHelp.setFixedWidth(self.width() * 0.2)  # تنظیم عرض به 20%
        self.button_layout.addWidget(self.buttonHelp)

        self.layout.addLayout(self.button_layout)

    def process_link(self):
        input_text = self.input_text.text().strip()
        if not input_text:
            self.show_error("Error", "Please enter a valid link")
            return

        if not input_text.startswith("http://") and not input_text.startswith("https://"):
            self.show_error("Error", "Please enter a valid link")
            return

        try:
            encoded_part = input_text.split('/')[-1]
            decoded_bytes = base64.b64decode(encoded_part)
            decoded_text = decoded_bytes.decode('utf-8')
            parts = decoded_text.split('$')

            if len(parts) != 3:
                self.show_error("Error", "Please enter a valid link")
                return

            data = {
                "url": decoded_text,
                "email": parts[0],
                "host": parts[1],
                "id": parts[2]
            }

            with open("data.json", "w", encoding='utf-8') as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
            url="https://"+parts[1]
            result,response = self.send_request_to_host(url,encoded_part)

            if result==True:

                print(response)


                # نمایش فیلد login
                login_status = response.get("login")
                print(login_status)
                if login_status=="True":
                    decoded_bytes = base64.b64decode(response.get("password"))
                    # تبدیل بایت‌ها به رشته با استفاده از utf-8
                    decoded_str = decoded_bytes.decode('utf-8')
                    print(decoded_str)
                    self.CheckPassword(decoded_str,response)

                else:
                    self.show_error("failed","Activation failed")



            else:
                self.show_error("Invalid","Invalid login token")
        except Exception as e:
            self.show_error("Error", "There was a problem processing the entered link")

    def send_request_to_host(self, host, token):
        info_connection = get_client_info()
        url = f"{host}/Frogment/Apis/Auth"
        headers = {
            "User-Agent": "Your User Agent",  # در صورت نیاز به استفاده از Bearer Token
            "Content-Type": "application/x-www-form-urlencoded"
        }

        payload = {
            'Token': token,
            'Ip': info_connection["ip_address"],
            'NameClinets': info_connection["hostname"]
        }

        try:
            response = requests.post(url, headers=headers, data=payload,verify=False)


            if response.status_code==200:
                # تبدیل پاسخ به فرمت JSON
                response_json = response.json()
                return True,response_json
            else:
                return False,None

        except requests.exceptions.HTTPError as err:
            print(err)
            return False ,None
        except Exception as err:
            print(err)
            return False ,None

    def CheckPassword(self,password,model):
        dialog = QDialog(self)
        dialog.setWindowTitle("Enter Password")
        dialog.setMinimumSize(300, 100)

        layout = QVBoxLayout(dialog)

        password_input = QLineEdit(dialog)
        password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(password_input)

        confirm_button = QPushButton("Confirm", dialog)
        confirm_button.clicked.connect(dialog.accept)
        layout.addWidget(confirm_button)

        dialog.setLayout(layout)

        dialog.exec_()
        if dialog.result() == QDialog.Accepted and password == password_input.text():
            with open("login.json", "w", encoding='utf-8') as file:
                json.dump(model, file, ensure_ascii=False, indent=4)
            self.show_Succ("Login", "Welcome To Em")
            self.open_welcome_window()
        else:
            self.show_error("Error", "Not Valid Password")

    def show_help(self):
        QMessageBox.information(self, "Help", "Get the activation link: You will receive an activation link from your administrator or in your email. Enter the link in the desired box and press the activation button")


    def show_error(self, title, message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.exec_()

    def show_Succ(self, title, message):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.exec_()

    def open_welcome_window(self):
        self.welcome_window = dashboard()
        self.welcome_window.show()
        self.close()

def get_client_info():
    # Get the hostname
    hostname = socket.gethostname()

    # Get the IP address
    ip_address = socket.gethostbyname(hostname)
    print(ip_address)
    print(hostname)
    # Create a dictionary with the information
    client_info = {
        "hostname": hostname,
        "ip_address": ip_address
    }

    return client_info

