
import os
import subprocess
import os.path
import time
import threading
import re
from xml.dom import minidom
from xml.parsers.expat import ExpatError
from config_fuzzer import RunParameters

def get_jacoco_coverage(restore_count, app_package_name, app_class_files_path, avd_serial):
    # adb shell am broadcast -a edu.gatech.m3.emma.COLLECT_COVERAGE
    cov_file_name = 'coverage' + str(restore_count)

    cmd = subprocess.Popen(['../../scripts/pull_coverage_jacoco.sh', cov_file_name, app_package_name, app_class_files_path, avd_serial, RunParameters.OUTPUT_DIR],
                           stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    output, err = cmd.communicate()
    print 'get_jacoco_coverage- return code: ' + ' output: ' + str(output) + ' ' + str(err) +' '

def compute_coverage_jacoco(app_class_files_path):
    #using compute_coverage to compute
    cmd = subprocess.Popen (['../../scripts/compute_coverage_jacoco.sh', app_class_files_path, RunParameters.OUTPUT_DIR],stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    output, err=cmd.communicate()
    print 'compute_coverage-return code: ' + ' output: '+str(output) + '  ' + str(err) +' '

def read_coverage_jacoco():
    if not os.path.isfile(RunParameters.OUTPUT_DIR+'/coverage.xml'):
        return 0

    try:
        # see the format of coverage report generated by Jacoco in xml
        xmldoc = minidom.parse(RunParameters.OUTPUT_DIR+'/coverage.xml')
        counters = xmldoc.getElementsByTagName('counter')
        line_coverage = 0
        for counter in counters:
            type_name = counter.getAttribute('type')
            if type_name == 'LINE':
                missed_lines = int(counter.getAttribute('missed'))
                covered_lines = int(counter.getAttribute('covered'))
                line_coverage = covered_lines * 1.0 / (missed_lines + covered_lines)

        if line_coverage == 0:
            return 0
        else:
            print "-----------"
            print "current jacoco line coverage rate: " + str(line_coverage)
            print "-----------"
            return line_coverage
    except ExpatError:
        print "parse xml error, catch it!"
        return 0

def read_current_coverage():
    return read_coverage_jacoco()

def compute_current_coverage(app_class_files_path):
    compute_coverage_jacoco(app_class_files_path)

def pull_coverage_files(restore_count, app_package_name, app_class_files_path, avd_serial):
    get_jacoco_coverage(restore_count, app_package_name, app_class_files_path, avd_serial)

# def record_coverage():
#     start_time = time.time()
#     file_path='../../output/coverage_time.csv'
#
#     #clear the old data
#     open(file_path,'w').close()
#
#     while True:
#         with open(file_path, 'a') as coverage_file:
#             t = time.time() - start_time
#
#             # compute_coverage()
#             # coverage = read_coverage()
#             # TODO, record_coverage() is not used in the project, so it is okay for now without giving proper parameters.
#             compute_coverage_jacoco()
#             coverage = read_coverage_jacoco()
#
#             line = str(round(t,1)) + "," + str(coverage) + "\n"
#             coverage_file.writelines(line)
#             coverage_file.flush()
#             coverage_file.close()
#
#         time.sleep(120)

