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,QFontDatabase
from PyQt5.QtCore import Qt
from qt_material import apply_stylesheet
import arabic_reshaper
from bidi.algorithm import get_display
from  langHandel import langHandel
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.language=langHandel("login")
        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(self.language.get_value( "title"))
        self.label.setAlignment(Qt.AlignCenter)
        font = QFont("", 16)
        self.label.setFont(font)
        self.layout.addWidget(self.label)

        self.input_text = QLineEdit()
        self.input_text.setAlignment(Qt.AlignCenter)
        self.input_text.setPlaceholderText(self.language.get_value( "input"))
        self.layout.addWidget(self.input_text)

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

        self.button = QPushButton(self.language.get_value( "btnActivation"))
        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(self.language.get_value( "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(self.language.get_value( "errorTitle"),  self.language.get_value( "validlinkErrorText"))
            return

        if not input_text.startswith("http://") and not input_text.startswith("https://"):
            self.show_error(self.language.get_value( "errorTitle"),  self.language.get_value( "validlinkErrorText"))
            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(self.language.get_value(  "errorTitle"),
                                self.language.get_value(  "validlinkErrorText"))

                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)
            print(result)
            print(response)
            if result==True:
                # نمایش فیلد 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(self.language.get_value(  "errorTitle"),
                                    self.language.get_value( "errorActiveText"))



            else:
                self.show_error(self.language.get_value(  "errorTitle"),
                                self.language.get_value( "errorTokenText"))
        except Exception as e:
            self.show_error(self.language.get_value(  "errorTitle"),
                            self.language.get_value(   "errorServerText"))

    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(self.language.get_value( "titlePassword"))
        dialog.setMinimumSize(300, 100)

        layout = QVBoxLayout(dialog)

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

        confirm_button = QPushButton(self.language.get_value( "confirmation"), 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():
            if(model.get("accessClinetConnect")=="access"):
                with open("login.json", "w", encoding='utf-8') as file:
                    json.dump(model, file, ensure_ascii=False, indent=4)
                self.show_Succ(self.language.get_value( "successfulTitle"), self.language.get_value( "successfulText"))
                self.open_welcome_window()
            else:
                self.show_error(self.language.get_value( "errorTitle"), self.language.get_value( "accessTitle"))
        else:
            self.show_error(self.language.get_value( "errorTitle"), self.language.get_value( "errorText"))

    def show_help(self):
        QMessageBox.information(self,self.language.get_value( "helpTitle"), self.language.get_value( "helpText"))


    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):
        try:
            self.welcome_window = dashboard()
            self.welcome_window.show()
            self.close()
        except:
            print("error opening")

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

