import os
import sys
import time

import uiautomator2 as u2
from cnocr import CnOcr


def spider_poc(serial):
    d = u2.connect(serial)
    d.screen_on()
    d.unlock()
    d.debug = False

    d.app_stop("com.facebook.katana")
    d.app_start("com.facebook.katana", use_monkey=True)
    time.sleep(3)

    # 搜索
    d.xpath('//*[@content-desc="搜索"]').click(timeout=3)
    d.xpath('//*[@text="搜索"]').click(timeout=3)
    d(focused=True).set_text('电子元器件')

    d.press('enter')

    root_dir = os.path.dirname(sys.argv[0])
    screenshot_name = f'screenshots/{time.time()}.png'
    screenshot_dir = os.path.join(root_dir, screenshot_name)
    d.screenshot().save(screenshot_dir)

    ocr = CnOcr()
    res = ocr.ocr(screenshot_dir)
    print(res)


if __name__ == '__main__':
    spider_poc('5D7HSG5XXCKVBI85')
