"""
This script updates the notes in the data-catalog for labbot-01 test runs.
For every note with a polarion test case id it finds - it adds a note with the corresponding testrail id.
It will only do this for notes in the dictionary defined in test_case_dict.py
If the note with the new test case id already exists it will create a duplicate copy.
"""

import re
from datetime import datetime
from dateutil.tz import tzlocal, tzutc
from infra.data_catalog.client import data_rest_api
from test_case_dict import test_case_dict

#%%
# Make polarion test case id to test rail test case id dictionary
test_case_dict_pol2tr = {v: k for k,v in test_case_dict.iteritems()}

#%%
START_TIME = datetime(2020,06,9)
END_TIME = datetime(2020,06,13)
runs = data_rest_api.get_runs(vehicle='labbot_01')
runs = data_rest_api.get_runs(vehicle='labbot_01', window_start=START_TIME, window_end=END_TIME)
for run in runs['runs']:
    print('-----------------------')
    print('Checking META-ID {}'.format(run['meta_id']))
    notes = data_rest_api.get_run_notes(run['data_id'])
    sequence=len(notes['notes'])
    
    # Get list of messages in run to later check if new message already exists before writing
    messages = []
    for note in notes['notes']:
        messages.append(note['message'])
    
    # Iterate through notes to make new messges
    for note in notes['notes']:
        message = note['message']

        # Find Test_Case_ID and make new message based on dictionary
        m = re.search(r'(\$Test_Case_ID) (\S*)', message)
        if m:
            test_case_id = m.group(2)
            if test_case_id in test_case_dict_pol2tr.keys():
                new_message = message.replace(test_case_id, test_case_dict_pol2tr[test_case_id])
    
                assert test_case_id == test_case_dict[test_case_dict_pol2tr[test_case_id]], 'Dictionary mismatch!'
                
                # Write only if new message does not exist already
                if new_message in messages:
                    print('Skipping message in meta id {} --- SKIPPED'.format(run['meta_id']))
                else:
                     data_id = note['data_id']
                     try:
                         event_time = datetime.strptime(note['timestamp'][:-6], '%Y-%m-%dT%H:%M:%S.%f')
                         pub_time = datetime.strptime(note['publish_timestamp'][:-6], '%Y-%m-%dT%H:%M:%S.%f')
                     except ValueError:
                         print('Value Error found. Using the new path')
                         event_time = datetime.strptime(note['timestamp'][:-6], '%Y-%m-%dT%H:%M:%S')
                         pub_time = datetime.strptime(note['publish_timestamp'][:-6], '%Y-%m-%dT%H:%M:%S')
                     print('Writing message: {}'.format(new_message))
                     data_rest_api.add_note(data_id=data_id, event_time=event_time, message=new_message ,pub_time=pub_time,sequence=sequence)
                     sequence = sequence+1
    
