"""
Created on 12/08/2019

@author: kristina ibanez-garikano

Compare EHdn outcome in duplicates or MZ twins
"""

import csv
import json
import os

# duplicated pairs
# WGS
l_id1 = ["171727", "171750", "115593", "118023"]
l_id2 = ["171766", "171669", "115417", "115330"]

# WES
#l_id1 = ["4236", "4226", "64625", "59095"]
#l_id2 = ["5433", "6029", "153135", "147004"]

post_file_name = "_EHdenovo.json"
work_dir = "/Users/kjzt780/CGR/kibanez/STRs/EHdeNovo/MZ_twins/output/output_slowerMoreSens"
#work_dir = "/Users/kjzt780/CGR/kibanez/STRs/EHdeNovo/MZ_twins/output/WES/output_slowerMoreSens"


# Let's enrich merge dictionary with ID1 and ID2 json files generated by EHdn
merge_dict = {}

for index, file_name in enumerate(l_id1):
    # MZ twin 1
    file_name1 = os.path.join(work_dir, file_name + post_file_name)
    with open(file_name1, "r") as read_file:
        file_name1_dict = json.load(read_file)

    file_name1_dict.pop("Depth")
    file_name1_dict.pop("ReadLength")

    # Enrich dict with MZ pair1
    for key, val in file_name1_dict.items():
        file_name1_dict[key]['mz_twin_1'] = True

    # MZ twin 2
    file_name2 = os.path.join(work_dir, l_id2[index] + post_file_name)
    with open(file_name2, "r") as read_file:
        file_name2_dict = json.load(read_file)

    file_name2_dict.pop("Depth")
    file_name2_dict.pop("ReadLength")

    # Enrich dict with MZ pair2
    for key, val in file_name2_dict.items():
        file_name2_dict[key]['mz_twin_2'] = True

    # Intersection between MZ twins/duplicates EHdn detected expansions
    keys_one = set(file_name1_dict.keys())
    keys_two = set(file_name2_dict.keys())
    intersection_one_two = keys_one & keys_two
    print(len(intersection_one_two))

    # Difference between MZ twins/duplicates EHdn detected expansions
    missing_in_dict1_but_in_dict2 = set(file_name1_dict) - set(file_name2_dict)
    print(len(missing_in_dict1_but_in_dict2))
    missing_in_dict2_but_in_dict1 = set(file_name2_dict) - set(file_name1_dict)
    print(len(missing_in_dict2_but_in_dict1))

    # Write the intersection, diff_dict1 and diff_dict2 into files
    file_dict1 = csv.writer(open(os.path.join(work_dir, "diff_" + l_id1[index] + '_notIn_' + l_id2[
        index] + '.txt'), 'w'),
                            delimiter='\n')
    file_dict1.writerow(list(missing_in_dict1_but_in_dict2))

    file_dict2 = csv.writer(open(os.path.join(work_dir, "diff_" + l_id2[index] + '_notIn_' + l_id1[
        index] + '.txt'), 'w'),
                            delimiter='\n')
    file_dict2.writerow(list(missing_in_dict2_but_in_dict1))

    file_intersection = csv.writer(open(os.path.join(work_dir, "intersection_" + l_id1[index] +
                                                     '_' + l_id2[index] + '.txt'), 'w'),
                                   delimiter='\n')
    file_intersection.writerow(list(intersection_one_two))



