from django.http import JsonResponse
from django.forms.models import model_to_dict
import time


def Validate(datas={}, required=[]):
    try:
        for e in required:
            if e not in datas.keys():
                return False
        newData = {}
        for data in datas.lists():
            if isinstance(data[1], list) and len(data[1]) == 1:
                newData[data[0]] = data[1][0]
            else:
                newData[data[0]] = data[1]
        return newData
    except e:
        return False


def isNotEmpty(datas={}, required=[]):
    newData = Validate(datas, required)
    if not newData:
        return False
    for key in newData.keys():
        value = newData[key]
        if key in required and isinstance(value, str) and len(value) == 0:
            return False
        elif key in required and isinstance(value, list) and len(value) == 0:
            return False
    return newData


def Rsl(body='', status=200):
    return JsonResponse(body, status=status, safe=False)


def ObjectListToListDic(object):
    datas = []
    o = list(object)
    for e in o:
        datas.append(model_to_dict(e))
    return datas


def file_directory_path(instance, filename):
    return type(instance).__name__ + '/{0}/{1}'.format(instance.id if instance.id else time.time(), filename)


def podcast_directory_path(instance, filename):
    return 'podcasts_files' + '/{0}/{1}'.format(instance.id if instance.id else time.time(), filename)
