from multiprocessing import Process
from threading import Timer

import json
import os
import time
import argparse

from adb import ADBException, ADBConnection
from utils import get_monitoring_methods, extract_method_classes
from jdwp import JDWPConnection, JDWPHelper

def monitor_func(device_id, apk_path_list, droidbot_out_dir,
                 trace_comparator_out_dir, output_dir,
                 timeout, tracing_interval, interval, is_emulator):
    """
    test apks on the assigned vm/device
    """
    for apk_path in apk_path_list:
        apk_label = apk_path.split("/")[-1][:-len(".apk")]
        full_output_dir = "%s/%s/" % (output_dir, device_id)
        if os.system("mkdir -p %s" % full_output_dir):
            print "failed mkdir -p %s" % full_output_dir
            continue

        app_droidbot_out_dir = "%s/%s" % (droidbot_out_dir, apk_label)

        # get package name by dumpsys_package file name
        package_name = [x for x in os.walk(app_droidbot_out_dir).next()[2]
                        if x.startswith("dumpsys")][0][len("dumpsys_package_"):-len(".txt")]

        # get event sequences by events/event_*.json
        droidbot_events = []
        event_paths = sorted([os.path.join(app_droidbot_out_dir, "events", x) for x in
                              os.walk(os.path.join(app_droidbot_out_dir, "events")).next()[2]
                              if x.endswith(".json")])

        # skip the first HOME KEY event
        for event_path in event_paths[1:]:
            with open(event_path, "r") as event_file:
                droidbot_events.append(json.load(event_file)["event"])

        # get monitoring method list from trace_comparator_output_dir
        # tid: methods
        monitoring_methods_list = []
        comparator_result_paths = ["%s/%s" % (trace_comparator_out_dir, x)
                                   for x in os.walk(trace_comparator_out_dir).next()[2]
                                   if x.startswith(apk_label)]
        comparator_result_labels = sorted([x.split("/")[-1][:-len(".json")] for x in comparator_result_paths])