package com.yang.hongbao.ui;

import android.accessibilityservice.AccessibilityService;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

/**
 * Created by ${Ян-Вэнь-Чао} on 2016/10/11.
 * //准备红包服务 开启
 */
public class HongBao extends AccessibilityService {
    private String[] filter = new String[]{"恭喜发财"};
    AccessibilityNodeInfo rootNodeInfo = null;
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        rootNodeInfo = event.getSource();
        if (rootNodeInfo == null) {
            return;
        }
        startClick(rootNodeInfo);
    }
//    git remote add origin https://git.oschina.net/YYCO/Hongbao.git
    private void startClick(AccessibilityNodeInfo rootNodeInfo) {
        List<AccessibilityNodeInfo> list = findByText(rootNodeInfo);
        if (list == null) {
            return;
        }
        AccessibilityNodeInfo nodeInfo1 = list.get(list.size() - 1);
        if (nodeInfo1 != null) {
            if ("已拆开".equals(rootNodeInfo.getText())) {
                return;
            }
                boolean isClick = nodeInfo1.getParent().performAction(
                        AccessibilityNodeInfo.ACTION_CLICK);

                if (!isClick) {
                    recleClick(rootNodeInfo);
                }
        }
    }

    private void recleClick(AccessibilityNodeInfo rootNodeInfo) {
        int child = rootNodeInfo.getChildCount();
        if (child == 0) {
            rootNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
        for (int i=0;i<child;i++) {
            AccessibilityNodeInfo info = rootNodeInfo.getChild(i);
            if (info == null) {
                continue;
            }
            if (info.getChildCount() > 0) {
                recleClick(info);
            } else {
                rootNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }

        }
    }

    private List<AccessibilityNodeInfo> findByText(AccessibilityNodeInfo rootNodeInfo) {
        for (String name : filter) {
            List<AccessibilityNodeInfo> list =
                    rootNodeInfo.findAccessibilityNodeInfosByText(name);
            if (list != null && !list.isEmpty()) {
                return list;
            }
        }
        return null;
    }
    @Override
    public void onInterrupt() {

    }
}