from datetime import datetime, date
from django.db.models.fields.files import ImageFieldFile
from collections import OrderedDict


def send_mail_alert_w_data(obj, data, user=None):

    # try:
    #
    #     article = getattr(obj, 'article', None)
    #     if article and article in ('10751', '10752', '10753', '10754', '10801', '10802', '10803', '10804'):
    #         from BaseModels.mailSender import techSendMail
    #         msg = f'change product {article}<br>' \
    #               f'{datetime.now()}<br>' \
    #               f'{str(user)}<br>' \
    #               f'obj = {str(obj.__dict__)}<br>' \
    #               f'data = {str(data)}<br>'
    #         techSendMail(msg, 'tE checkpoint alert')
    #
    # except Exception as e:
    #     print(f'send_mail_alert_w_data ERROR = {str(e)}')

    return True



def get_normalized_data(data):

    if type(data) == OrderedDict:
        data = dict(data)

    if '_state' in data:
        del data['_state']

    if type(data) == dict:
        for key, val in data.items():
            if type(data[key]) in (dict, list, OrderedDict):
                data[key] = get_normalized_data(val)
            if type(data[key]) in (datetime, date, ImageFieldFile):
                data[key] = str(val)

    if type(data) == list:
        i = 0
        while i < len(data):
            # if type(item) == OrderedDict:
            #     item = dict(item)
            item = data[i]

            if type(item) in (dict, list, OrderedDict):
                data[i] = get_normalized_data(item)

            if type(item) == dict:
                for key, val in item.items():
                    if type(item[key]) in (datetime, date, ImageFieldFile):
                        item[key] = str(val)

            elif type(item) == list:
                ei = 0
                while ei < len(item):
                    if type(item[ei]) in (datetime, date, ImageFieldFile):
                        item[ei] = str(item[ei])

                    ei += 1

            i += 1

    return data



def prepare_data_for_json(data):

    data = get_normalized_data(data)

    # if type(data) == OrderedDict:
    #     data = dict(data)
    #
    # if '_state' in data:
    #     del data['_state']
    #
    # if type(data) == dict:
    #     for key, val in data.items():
    #         if type(data[key]) in (datetime, date, ImageFieldFile):
    #             data[key] = str(val)
    #
    # if type(data) == list:
    #     for item in data:
    #         if type(item) == OrderedDict:
    #             item = dict(item)
    #
    #         if type(item) == dict:
    #             for key, val in item.items():
    #                 if type(data[key]) in (datetime, date, ImageFieldFile):
    #                     item[key] = str(val)
    #
    #         elif type(item) == list:
    #             for el in item:
    #                 if type(el) in (datetime, date, ImageFieldFile):
    #                     el = str(el)



    return data