from Main.models.categories import Category, Product_category
from Main.models.products import Product
from Main.utilities.logs import logError

from django.utils import timezone
import datetime

def getCategoryFromProduct(product):
    
    category = Product_category.objects.filter(product_id=product["id"])[0].category.get_as_dict()
    
    category2 = None
    category1 = None
    category0 = None
    
    try:
        if category["level_depth"] == 2:
            category2 = category
            category1 = Category.objects.get(id=category["parent_id"]).get_as_dict()
            category0 = Category.objects.get(id=category2["parent_id"]).get_as_dict()
        elif category["level_depth"] == 1:
            category1 = category
            category0 = Category.objects.get(id=category1["parent_id"]).get_as_dict()
        else:
            category0 = category
    except:
        logError("category not found on product page id:" + str(product["id"]))
        return {"category0": category}
    
    return {
        "category2": category2,
        "category1": category1,
        "category0": category0
    }
    
def getDailyDeals():
    #todo modify to get the actual deals
    products = Product.objects.filter(daily_deal=True)[:5]
    tmp = []
    
    end = (timezone.localtime(timezone.now()) + datetime.timedelta(days=1)).strftime('%m/%d/%Y 00:00:00')

    for prod in products:
        tmp.append(prod.get_as_big_dict())
        
    return {
        "products": tmp,
        "endtime": end
    }
    
def getLayoutCategories():
    categories = Category.objects.filter(active=True, level_depth=0).order_by('position')
    final_categories = []
    
    for category in categories:
        final_categories.append(category.get_as_dict())
        
    return final_categories
    
def getMainDict():
    return {
        "layoutCategories": getLayoutCategories()
    }