# vim: ai ts=4 sts=4 et sw=4
from django.http import HttpResponse
from django.template import Context,loader
from obchod.main.models import *
from django import forms

class TovarForm(forms.Form):
    pocet=forms.IntegerField(required=True,\
		initial=1)

class ObchodContext(Context):
    
    def __init__(self,request,d):
        Context.__init__(self,d)
        if 'kosik' not in request.session:
            request.session['kosik']=[]
        self['pocet_kosik']=len(request.session['kosik'])
        self['suma_kosik']=sum(
            polozka.tovar.cena*polozka.pocet 
                for polozka in request.session['kosik'])	
        self['kategorie']=Kategoria.objects.all()

class Polozka(object):
    
    def __init__(self,tovar,pocet):

        self.tovar=tovar
        self.pocet=pocet
    

def tovar(request,nazov):
    tovary=Tovar.objects.filter(nazov=nazov)
    tovar=tovary[0]
    if request.method=='POST':
        f=TovarForm(request.POST)
        if f.is_valid():
            pocet=f.cleaned_data['pocet']
            if 'kosik' not in request.session:
                request.session['kosik']=[]
            request.session['kosik']+=[Polozka(tovar,pocet)]
            t=loader.get_template('kosik_pridaj.html')
            c=ObchodContext(request,{'tovar':tovar})
            html=t.render(c)
            return(HttpResponse(html))
    else:
        f=TovarForm()
    t=loader.get_template('tovar.html')
    c=ObchodContext(request,{'tovar':tovar,'form':f})
    html=t.render(c)
    return(HttpResponse(html))

def kategoria(request,nazov):
    kategoria=Kategoria.objects.get(nazov=nazov)
    tovary=kategoria.tovar_set.all()
    t=loader.get_template('kategoria.html')
    c=ObchodContext(request,{'kategoria':kategoria, 'tovary':tovary})
    html=t.render(c)
    return(HttpResponse(html))

    
def kosik(request):
    t=loader.get_template('kosik.html')
    if 'kosik' not in request.session:
	    request.session['kosik']=[]
    c=ObchodContext(request,{'kosik':request.session['kosik']})
    html=t.render(c)
    return(HttpResponse(html))

def index(request):

    t=loader.get_template("index.html")
    c=ObchodContext(request,{})
    html=t.render(c)
    return(HttpResponse(html))


