from zlapi.models import Message, Mention, MultiMsgStyle, MessageStyle
import time
import threading
from config import ADMIN
import logging

# Cấu hình logging
logging.basicConfig(
    filename='var.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

des = {
    'version': "1.0.4",
    'credits': "Hồ Văn Hoà",
    'description': "Kết hợp chức năng tagall và chửi",
    'power': "Quản trị viên Bot"
}

is_var_running = False

def stop_var(client, message_object, thread_id, thread_type):
    global is_var_running
    is_var_running = False
    if message_object:
        client.replyMessage(Message(text="Success!"), message_object, thread_id, thread_type)
    else:
        client.sendMessage(Message(text="Success!"), thread_id, thread_type)
    logger.info(f"Stopped var command in thread {thread_id}")

def is_admin(author_id):
    return author_id in ADMIN  # Kiểm tra author_id có trong danh sách ADMIN

def send_error_message(client, thread_id, thread_type, error_message, message_object=None):
    if message_object:
        client.replyMessage(Message(text=error_message), message_object, thread_id, thread_type)
    else:
        client.sendMessage(Message(text=error_message), thread_id, thread_type)
    logger.error(f"Error in thread {thread_id}: {error_message}")

def handle_var_command(message, message_object, thread_id, thread_type, author_id, client):
    global is_var_running
    logger.info(f"Received command: {message}, thread_id: {thread_id}, author_id: {author_id}, thread_type: {thread_type.name}")

    command_parts = message.split()
    if len(command_parts) < 2:
        send_error_message(client, thread_id, thread_type, "on/off", message_object)
        return

    # Kiểm tra quyền admin
    if not is_admin(author_id):
        send_error_message(client, thread_id, thread_type, "Chỉ admin mới có thể sử dụng.", message_object)
        return

    action = command_parts[1].lower()

    if action == "off":
        if not is_var_running:
            send_error_message(client, thread_id, thread_type, "Success!", message_object)
        else:
            stop_var(client, message_object, thread_id, thread_type)
        return

    if action != "on":
        send_error_message(client, thread_id, thread_type, "on/off", message_object)
        return

    try:
        with open("data/noidung.txt", "r", encoding="utf-8") as file:
            Ngon = file.readlines()
    except FileNotFoundError:
        send_error_message(client, thread_id, thread_type, "Không tìm thấy tệp noidung.txt", message_object)
        return
    except Exception as e:
        send_error_message(client, thread_id, thread_type, f"Lỗi khi đọc tệp: {e}", message_object)
        return
    if not Ngon:
        send_error_message(client, thread_id, thread_type, "Tệp nội dung rỗng", message_object)
        return

    is_var_running = True
    def var_loop():
        while is_var_running:
            for noidung in Ngon:
                if not is_var_running:
                    break
                noidung = noidung.strip()
                mention = Mention("-1", length=len(noidung), offset=0)
                styles = MultiMsgStyle([
                    MessageStyle(offset=0, length=10000, style="font", size="100000", auto_format=False),
                    MessageStyle(offset=0, length=10000, style="bold", size="100000", auto_format=False),
                    MessageStyle(offset=0, length=10000, style="color", color="#db342e", auto_format=False),
                ])
                try:
                    client.send(Message(text=noidung, mention=mention, style=styles), thread_id, thread_type)
                    time.sleep(0.5)
                except Exception as e:
                    logger.error(f"Error sending message in thread {thread_id}: {e}")
                    break

    var_thread = threading.Thread(target=var_loop)
    var_thread.start()
    logger.info(f"Started var command in thread {thread_id}")

def ft_vxkiue():
    return {
        'var': handle_var_command
    }