import argparse
import multiprocessing
import os
import time
import json
import sys


def log_info(*args):
    log_str = "[*] "
    for curr_a in args:
        log_str = log_str + " " + str(curr_a)
    print log_str


def log_error(*args):
    log_str = "[!] "
    for curr_a in args:
        log_str = log_str + " " + str(curr_a)
    print log_str


def log_warning(*args):
    log_str = "[?] "
    for curr_a in args:
        log_str = log_str + " " + str(curr_a)
    print log_str


def log_success(*args):
    log_str = "[+] "
    for curr_a in args:
        log_str = log_str + " " + str(curr_a)
    print log_str


def setup_args():
    parser = argparse.ArgumentParser(description="Script that converts DR.CHECKER LLVM based jsons to jsons "
                                                 "containing source code info.")

    parser.add_argument('-d', action='store', dest='dr_jsons',
                        help='Destination directory where all the DR.CHECKER jsons should be read from.')

    parser.add_argument('-o', action='store', dest='output_jsons',
                        help='Destination directory where all the post-processed jsons should be stored.')

    parser.add_argument('-k', action='store', dest='kernel_src_dir', default=None,
                        help='Absolute path to the kernel sources.')

    parser.add_argument('-r', action='store', dest='original_src_dir', default=None,
                        help='Path to the original kernel sources, that should be replaced with alternate source dir.')

    parser.add_argument('-n', action='store', dest='new_src_dir', default=None,
                        help='Path to the new kernel sources, that should be used instead or original src dir.')

    return parser


def read_file_line(lineno, given_file, k_src, o_src, a_src):
    """
        Read the source line from the provided llvm line info
    :param lineno: line number to read from.
    :param given_file: file path in the original json
    :param k_src: Absolute path to the kernel sources.
    :param o_src: Path to the original kernel sources, that should be replaced with alternate source dir.
    :param a_src: Path to the new kernel sources, that should be used instead or original src dir.
    :return: None
    """
    if lineno <= 0:
        return ""

    if o_src is not None and a_src is not None:
        if os.path.isabs(given_file):
            given_file = given_file.replace(o_src, a_src)

    if not os.path.isabs(given_file):
        if k_src is not None:
            given_file = os.path.join(k_src, given_file)

    if os.path.exists(given_file) and os.path.isfile(given_file):
        fp = open(given_file, "r")
        all_lines = fp.readlines()
        to_ret = ""
        if len(all_lines) >= lineno:
            to_ret = all_lines[lineno-1].strip()
        return to_ret
    return ""