import random
import time
import wda
import os
from Utils.AiUtils import AiUtils
from Utils.ControlUtils import ControlUtils
from Utils.LogManager import LogManager


# 脚本管理类
class ScriptManager():

    # 单利对象
    _instance = None  # 类变量，用于存储单例实例

    def __new__(cls):
        # 如果实例不存在，则创建一个新实例
        if cls._instance is None:
            cls._instance = super(ScriptManager, cls).__new__(cls)
        # 返回已存在的实例
        return cls._instance

    def __init__(self):
        super().__init__()
        self.initialized = True  # 标记已初始化

    # 养号
    def growAccount(self, udid, event):
        client = wda.USBClient(udid)
        session = client.session()
        session.appium_settings({"snapshotMaxDepth": 15})

        # 检测当前打开的是否是Tik Tok。如果不是就打开
        ControlUtils.openTikTok(session)
        time.sleep(3)

        # 创建udid名称的目录
        AiUtils.makeUdidDir(udid)

        # 假设此时有个开关
        while not event.is_set():
            try:
                img = client.screenshot()
                filePath = f"resources/{udid}/bgv.png"
                img.save(filePath)
                LogManager.info("保存屏幕图像成功", udid)
                print("保存了背景图")
                time.sleep(1)
            except Exception as e:
                LogManager.error(e, udid)
                print(e)

            try:
                # 判断视频类型
                addX, addY = AiUtils.findImageInScreen("add", udid)
                isSame = False
                for i in range(2):
                    tx, ty = AiUtils.findImageInScreen("add", udid)
                    if addX == tx and addY == ty:
                        isSame = True
                        time.sleep(1)
                    else:
                        isSame = False
                        break

                # 如果找到普通视频
                if addX > 0 and isSame:
                    needLike = random.randint(0, 10)
                    # 查找首页按钮
                    homeButton = AiUtils.findHomeButton(udid)
                    if homeButton:
                        print("查看视频")
                        videoTime = random.randint(5, 15)
                        time.sleep(videoTime)

                        # 百分之三的概率点赞
                        if needLike < 3:
                            print("点赞")
                            ControlUtils.clickLike(session, udid)

                        print("继续观看视频")
                        videoTime = random.randint(10, 30)
                        time.sleep(videoTime)
                        print("准备划到下一个视频")
                        client.swipe_up()
                    else:
                        print("目前没有首页按钮。需要另外处理")
                else:
                    nextTime = random.randint(1, 5)
                    time.sleep(nextTime)
                    client.swipe_up()
            except Exception as e:
                print(f"发生异常：{e}")
                client.swipe_up()

# manager = ScriptManager()
# manager.growAccount("eca000fcb6f55d7ed9b4c524055214c26a7de7aa")

