from .mailSender import techSendMail



# def get_order_changes_list_for_template(order):
#
#     if order.json_data and 'data_log' in order.json_data:
#
#         i = 0
#         changes_log = []
#
#         if len(order.json_data['data_log']) > 0:
#             first_log_record = order.json_data['data_log'][0]
#
#             while i<len(order.json_data['data_log'])-1:
#                 dict1 = order.json_data['data_log'][i]['order_data']
#                 dict2 = order.json_data['data_log'][i+1]['order_data']
#
#                 res = {'order' : dict_compare(dict1, dict2)}
#                 rec_DT = res['order']['modified']['now_DT'][1]
#                 del res['order']['modified']['now_DT']
#
#                 # for item in res['order'].values():
#                 #     if type(item) == set:
#                 #         item = list(item)
#
#                 # dishes_set1 = order.json_data['data_log'][i]['dishes_data'])
#                 # dishes_set2 = set(order.json_data['data_log'][i+1]['dishes_data'])
#                 # res = dishes_set1.symmetric_difference(dishes_set2)
#                 # dict1 = {'dishes': order.json_data['data_log'][i]['dishes_data']}
#                 # dict2 = {'dishes': order.json_data['data_log'][i + 1]['dishes_data']}
#                 list1 = []
#                 list2 = []
#                 list1.extend(order.json_data['data_log'][i]['dishes_data'])
#                 list2.extend(order.json_data['data_log'][i + 1]['dishes_data'])
#                 # res['modified'].
#                 res.update({'dishes' : list_compare(list1, list2)})
#                 changes_log.append({rec_DT: res})
#
#                 i += 1
#
#             return {
#                 'changes_log' : changes_log,
#                 'first_log_record' : first_log_record
#             }
#
#     return {}



def get_changes_for_Dicts(old_Dict, newDict):

    res = {}
    required_save = False

    try:

        # order_Dict = get_orderDict_by_order(order)


        # if order.json_data and 'data_log' in order.json_data:
        #     last_rec = order.json_data['data_log'][-1]

        res = dict_compare(old_Dict, newDict)
        # del res['modified']['now_DT']
        if res and (res['modified'] or res['added'] or res['removed']):
            required_save = True

        # res = dict_compare({'dishes' : last_rec['dishes_data']}, {'dishes' : order_Dict['dishes_data']})
        # if res['modified'] or res['added'] or res['removed']:
        #     required_save = True
        # else:
        #     required_save = True

        # json_data = order.json_data
        # if required_save:
        #     if not json_data:
        #         json_data = {}
        #     if not 'data_log' in json_data:
        #         json_data.update({'data_log' : []})
        #
        #     json_data['data_log'].append(order_Dict)

    except Exception as e:

        msg = 'get_changes_for_Dicts Error = {0}<br>{1}'.format(str(e), str(e.args))
        print(msg)
        techSendMail(msg)

    return res, required_save




def list_compare(old_data_list, new_data_list):

    res = {
        'added': [],
        'removed': [],
        'modified': [],
    }

    old_list = []
    old_list.extend(old_data_list)
    new_list = []
    new_list.extend(new_data_list)

    if new_list == old_list:
        return {}


    i2 = 0
    list_w_id = False
    while i2 < len(new_list):
        req_del = False
        i1 = 0

        if 'id' in new_list[i2]:
            list_w_id = True
            while i1 < len(old_list):
                if old_list[i1] == new_list[i2]:
                    req_del = True
                else:

                    if old_list[i1]['id'] == new_list[i2]['id']:
                        if type(old_list[i1]) == dict:
                            res_dict_compare = dict_compare(old_list[i1], new_list[i2])
                            if 'property' in new_list[i2]:
                                res['modified'].append({new_list[i2]['property']['name']: res_dict_compare})
                            else:
                                res['modified'].append({new_list[i2]['id']: res_dict_compare})
                        elif type(old_list[i1]) in [tuple, list]:
                            res_list_compare = list_compare(old_list[i1], new_list[i2])
                            res['modified'].append(res_list_compare)
                        else:
                            res['modified'].append(new_list[i2])

                        req_del = True
                    # else:
                    #     i1 += 1




                if req_del:
                    del old_list[i1]
                    del new_list[i2]
                    break
                else:
                    i1 += 1
        else:
            if not new_list[i2] in old_list:
                if i2 < len(old_list):
                    res['modified'].append([old_list[i2], new_list[i2]])
                    del old_list[i2]
                else:
                    res['modified'].append(new_list[i2])
                del new_list[i2]
                continue
            else:
                i2 += 1

            req_del = True



        # если не была найдена в обоих списках - значит добавлена
        if not req_del:
            res['added'].append(new_list[i2])
            del new_list[i2]
        # else:
        #     i2 += 1

    if list_w_id and old_list:
        res['removed'].extend(old_list)

    if res['added'] or res['modified'] or res['removed']:
        return res

    return {}



def dict_compare(old_d2, new_d1):


    added = []
    removed = []
    modified = []

    if not old_d2 and not new_d1:
        return {}

    try:
        if not old_d2 and new_d1:
            added.append('None > ' + str(new_d1))
            # for val, key in new_d1.items():
            #     added.update({key: (None, val)})
        elif not new_d1 and old_d2:
            # modified = (old_d2)
            # removed = {}
            # for val, key in old_d2.items():
            #     removed.update({key: (None, val)})
            removed.append(str(old_d2) + ' > None')
        else:
            d1_keys = set(new_d1.keys())
            d2_keys = set(old_d2.keys())
            intersect_keys = d1_keys.intersection(d2_keys)
            added = d1_keys - d2_keys
            removed = d2_keys - d1_keys
            modified = {}
            for o in intersect_keys:
                if new_d1[o] != old_d2[o]:
                    if type(new_d1[o]) == dict:
                        modified.update({
                            o: dict_compare(old_d2[o], new_d1[o])
                        })
                    elif type(new_d1[o]) in [list, tuple]:
                        modified.update({
                            o: list_compare(old_d2[o], new_d1[o])
                        })
                    else:
                        modified.update({
                            o: (old_d2[o], new_d1[o])
                        })
            # modified = {o : (new_d1[o], old_d2[o]) for o in intersect_keys if new_d1[o] != old_d2[o]}
            same = set(o for o in intersect_keys if new_d1[o] == old_d2[o])

        # if not added:
        #     added = []
        # if not removed:
        #     removed = []
        # if not modified:
        #     modified = []


        if added or removed or modified:
            return {
                'added': added,
                'removed': removed,
                'modified': modified,
                # 'added' : list(added),
                # 'removed' : list(removed),
                # 'modified' : list(modified),
                # 'same' : same
            }

    except Exception as e:

        msg = 'dict_compare Error = {0}<br>{1}<br>{2}<br>{3}'.format(
            str(e),
            str(e.args),
            old_d2,
            new_d1
        )
        print(msg)
        techSendMail(msg)

    return {}
