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(brand, done, en=0):
    all_texts = brand.sibling(className="android.widget.TextView")
    res = []
    for text in all_texts:
        st = text.get_text()
        if st in done:
            return None
        if st in ["进入品牌", ""]:
            continue
        elif st.startswith("代表单品"):
            continue
        else:
            res.append(st)
    if len(res) in [3, 4]:
        done.append(res[0])
        if len(res) == 3:
            if en == 0:
                res.insert(1, "")
            else:
                res.insert(0, "")
        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 = None
        brands = d(className="android.support.v7.widget.RecyclerView").child(resourceId="org.c2h4.afei.beauty:id/tv_name")
        for temp in brands:
            if temp.info['bounds']['top'] == temp.info['visibleBounds']['top']:
                brand = temp
                break

        res = getBrandDetail(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(brands[idx], done)
        if res is not None:
            f.writelines(delim.join(res))
            print(delim.join(res) + "\n")
            getBrandImg(d, res[0])

    f.flush()
    f.close()

def getEnglishBrands():
    d = u2.connect_usb('d52196830204')

    done = []
    with open(brand_dir+"/brands.csv", "r") as f:
        for line in f.readlines():
            done.append(line.split("; ")[1].strip())
    print(done)

    f = open(brand_dir+"/brands.csv", 'a+')
    nocnt = 0
    while True:

        brand = None
        brands = d(className="android.support.v7.widget.RecyclerView").child(resourceId="org.c2h4.afei.beauty:id/tv_name_en")
        for temp in brands:
            if temp.info['bounds']['top'] == temp.info['visibleBounds']['top']:
                brand = temp
                break

        res = getBrandDetail(brand, done, 1)
        if res is not None:
            print(delim.join(res))
            f.write(delim.join(res) + "\n")
            getBrandImg(d, res[1])
            nocnt = 0
        else:
            nocnt += 1
        if nocnt == 10:
            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_en")
    for idx in range(1, brands.count):
        res = getBrandDetail(brands[idx], done, 1)
        if res is not None:
            f.writelines(delim.join(res))
            print(delim.join(res) + "\n")
            getBrandImg(d, res[1])

    f.flush()
    f.close()

if __name__=='__main__':
    # getAllBrands()
    getEnglishBrands()
