import json
import re
import sys

data = []

#Filtruje vsetky potrebne udaje pre dalsie spracovanie, vybera vrcholy zarovnania a rata casti, ktore sa k danym vrcholom zarovnali
def one_line_parse(one_line, out_file):
    name = one_line['name']
    out_file.write(name + '\t')
    path = one_line['path']
    mapping = path['mapping']
    cur_pos = 0
    if 'query_position' in one_line:
        cur_pos += one_line['query_position']
    sign = ''
    path = []
    for mid in mapping:
        pos = mid['position']
        edit = mid['edit']
        if 'node_id' not in pos:
            continue
        id = pos['node_id']
        cur_sum = 0
        if 'is_reverse' in pos and pos['is_reverse'] == True:
            sign = '-'
        else:
            sign = '+'
        for block in edit:
            if 'to_length' in block:
                cur_sum += int(block['to_length'])
        path.append(sign + str(id) + '\t' + str(cur_pos) + '\t' +str(cur_pos + cur_sum) + '\t')
        cur_pos += cur_sum
    for p in path:
        out_file.write(p)
    out_file.write('\n')
    return cur_pos

#Ako vstup berie json subor s cestou a vystupny subor(musi byt ukoncene _rwp_bp pre dalsie spracovanie)
arguments = sys.argv
json_file = arguments[1]
file_name = arguments[2]

#Parsuje json subor zarovnani po jednotlivych zarovnaniach - json objektoch
with open(json_file) as json_file:
    for line in json_file:
        data.append(json.loads(line))
    out_file = open(file_name,"w+")
    cur_pos = 0
    for one_line in data:
        one_line_parse(one_line, out_file)
    out_file.close