import cv2
import uiautomator2 as u2
import numpy as np

brand_dir = "brands"
delim = "; "

def cropImg(img, out, bounds):
    cropped = img[int(bounds['top']):int(bounds['bottom']), int(bounds['left']):int(bounds['right'])]  # 裁剪坐标为[y0:y1, x0:x1]
    cv2.imwrite(out, cropped)

def getBrandDetail(d, brand, done):
    all_texts = brand.sibling(className="android.widget.TextView")
    name = all_texts[0].get_text()
    if name not in done:
        res = []
        for text in all_texts:
            st = text.get_text()
            if st in ["进入品牌", ""]:
                continue
            elif st.startswith("代表单品"):
                continue
            else:
                res.append(st)
        if len(res) in [3, 4]:
            if len(res) == 3:
                res = [res[0]] + res
            done.append(name)
            return res
        else:
            return None

def getBrandImg(d, name):
    elems = d(className="android.support.v7.widget.RecyclerView").child(className="android.widget.RelativeLayout")
    imgele = None
    for idx in range(elems.count):
        elemIdx = elems.count - 1 - idx
        elem = elems[elemIdx]
        if elem.child(text=name).count == 1:
            imgele = elems[elemIdx - 1].child(resourceId="org.c2h4.afei.beauty:id/sriv")
            break
    if imgele is None:
        print("Can't find image for %s" % name)
    image = d.screenshot()
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
    outpath = "%s/%s.jpg" % (brand_dir, name)
    cropImg(image, outpath, imgele.info['visibleBounds'])

def getAllBrands():
    d = u2.connect_usb('d52196830204')
    # print(d.dump_hierarchy())
    f = open(brand_dir+"/brands.csv", 'a+')
    done = []
    nocnt = 0
    while True:
        brand = d(className="android.support.v7.widget.RecyclerView").child(resourceId="org.c2h4.afei.beauty:id/tv_name")[0]
        res = getBrandDetail(d, brand, done)
        if res is not None:
            print(delim.join(res))
            f.write(delim.join(res) + "\n")
            getBrandImg(d, res[0])
            nocnt = 0
        else:
            nocnt += 1
        if nocnt == 5:
            break
        d.swipe_ext("up", scale=0.2)
    brands = d(className="android.support.v7.widget.RecyclerView").child(resourceId="org.c2h4.afei.beauty:id/tv_name")
    for idx in range(1, brands.count):
        res = getBrandDetail(d, brands[idx], done)
        if res is not None:
            f.writelines(delim.join(res))
            print(delim.join(res) + "\n")
            getBrandImg(d, res[0])

    # while True:
    #     brand = d(className="android.support.v7.widget.RecyclerView").child(resourceId="org.c2h4.afei.beauty:id/tv_name_en")[0]
    #     res = getBrandDetail(d, brand, done)
    #     if res is not None:
    #         print(delim.join(res))
    #         f.writelines(delim.join(res))
    #     d.swipe_ext("down", scale=0.2)


if __name__=='__main__':
    getAllBrands()
