from .models import Store, PostCategory, Post, MenuItem
from .pos import MessageSys
from itertools import chain

class StoreFront:
    def __init__(self, storeId):
        self.store = Store.objects.get(pk=storeId)
        self.messageSys = MessageSys(self.store)

    @property
    def storeId(self):
        return self.store.id

    @classmethod
    def globalSearch(cls, q):
        qs1 = Post.objects.filter(title__icontains=q)
        qs2 = MenuItem.objects.filter(name__icontains=q)
        return list(chain(qs1, qs2))

    def primaryMenus(self):
        pass

    def secondaryMenus(self):
        pass

    @property
    def addressText(self):
        return self.store.addressText

    def search(self, **kwargs):
        print("Search")
        q = kwargs.get('q', None)
        if q:
            qs1 = Post.objects.filter(title__icontains=q, store=self.store)
            qs2 = MenuItem.objects.filter(name__icontains=q, store=self.store)
            return list(chain(qs1, qs2))
        else:
            return []

    def addToCart(self, orderId, menuId):
        pass

    def viewCart(self, orderId):
        pass

    def messageForm(self, oid=None, request=None):
        return self.messageSys.form(oid, request)

    @property
    def fullName(self):
        return f"{self.store.name}"

    def getPosts(self, **kwargs):
        cat = kwargs.get('cat', None)
        try:
            if cat:
                pc = PostCategory.objects.get(name=cat)
                return pc.post_set.filter(store=self.store)
        except:
            return None

    def getPostById(self, pid):
        return Post.objects.get(pk=pid)


    def getMenus(self, **kwargs):
        return self.store.menuitem_set.filter(**kwargs)

    @property
    def logo(self):
        if self.store.logo:
            return self.store.logo.url
        else:
            return None

    @property
    def description(self):
        return self.store.description

    @property
    def location(self):
        return (self.store.address, self.store.geolocation)


    @property
    def tel_number(self):
        return self.store.phone_number

    @property
    def fax_number(self):
        return self.store.fax_number

    @property
    def lineId(self):
        return self.store.lineId

    @property
    def email(self):
        return self.store.email


