import random
import time
import wda

from Utils.AiUtils import AiUtils
from Utils.ControlUtils import ControlUtils


# 脚本管理类
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)

        # 假设此时有个开关
        while not event.is_set():
            try:
                img = client.screenshot()
                filePath = "resources/bgv.png"
                img.save(filePath)
            except Exception as e:
                print(e)

            # 判断视频类型。普通视频、广告、直播，只有普通视频停留。其他视频全部划走
            addX, addY = AiUtils.findImageInScreen("add")
            # 如果找到普通视频
            if addX > 0:
                needLike = random.randint(0, 10)

                # 随机时间间隔
                videoTime = random.randint(2,5)
                time.sleep(videoTime)

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

                # 随机时间间隔
                # videoTime = random.randint(10,30)
                # time.sleep(videoTime)
                session.swipe_up()
            else:
                # 随机时间
                nextTime = random.randint(1,5)
                time.sleep(nextTime)
                session.swipe_up()
                continue

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

