def mark_wishlist_purchased(request, pk):
    dictionary = baseDict(request)

    purchased = WishlistItem.objects.get(pk=pk)
    purchased.bought = True
    bp = dictionary['bankingPerson']
    bp.wishlistSpending += purchased.price
    bp.save()
    purchased.save()
    now = datetime.datetime.now()
    dictionary = baseDict(request)
    second_date = datetime.date(now.year, now.month-1,1)
    pastBudgets = MonthlyBudget.objects.filter(date__lte=second_date)
    totalSaved = 0

    savingsCategories = []
    for pbudget in pastBudgets:
        savingsCategories.append(Category.objects.filter(budget=pbudget))
    total = 0
    spent = 0

    for i in savingsCategories:
        total += i[0].price
        spent += i[0].spent + dictionary['bankingPerson'].wishlistSpending

    dictionary.update({
        'pastSavings':  pastBudgets,
        'saved': total-spent,
        'wishlist': WishlistItem.objects.filter(user=request.user, bought=False),
    })

    return render_to_response("budget/get_saved_money.html", dictionary)
def add_category(request):
    dictionary = baseDict(request)
    today = datetime.date.today()
    formError = []

    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            monthlyBudget = form.cleaned_data['budget'].pk
            newCategoryPrice = form.cleaned_data['price']
            otherCategory = Category.objects.get(budget=monthlyBudget, title="Other", date__year=today.year, date__month=today.month,) # fetch the other section so you can decrease the amount, also for validation
            if otherCategory.price - otherCategory.spent < newCategoryPrice:
                formError.append("You can allocate " + str(otherCategory.price - otherCategory.spent) + ", but you tried to add " + str(newCategoryPrice))
            else:
                otherCategory.price -= newCategoryPrice # if the amount is not exeeding the other category, decrease the other category and create a new one
                otherCategory.save()
                form.save()
                dictionary.update({
                    "message" : "Category added !",
                })
                return render_to_response("alert.html",dictionary)

    else:
        form = CategoryForm()

    dictionary.update({
        "form": form,
        "formError": formError,
    })

    return render_to_response("budget/forms/add_category.html", dictionary, context_instance=RequestContext(request))
def past_budgets(request): # fetch past budgets
    dictionary = baseDict(request)
    budgets = MonthlyBudget.objects.all()
    dictionary.update({
        "budgets" : budgets, 
    })
    return render_to_response("budget/past_budgets.html", dictionary)
def story(request, slug=None):
    dictionary = baseDict(request)
    story = UserStory.objects.get(slug=slug)

    dictionary.update({"story": story})

    return render_to_response("controller/story.html", dictionary)
def wishlist(request, pk):
    dictionary = baseDict(request)
    wishlistItems = WishlistItem.objects.all()

    dictionary.update({
        "wishlistItems" : wishlistItems,
    })
    return render_to_response("budget/wishlist.html", dictionary)
def fullMessage(request,pk):
	myDict = baseDict(request)
	singleMessage = Notification.objects.get(pk=pk, to=request.user)
	singleMessage.read = True
	singleMessage.save()
	myDict.update({
		'message' : singleMessage
	})
	return render_to_response("notification/fullview.html", myDict)
def viewProfile(request):
    
    dictData = baseDict(request)
    bankingP = dictData['bankingPerson']
    outgoingTransactions = OutgoingTransaction.objects.filter(fromUser = request.user)
    incomingTransactions = IncomingTransaction.objects.filter(toUser = request.user)

    dictData.update({
        "outgoing": outgoingTransactions,
        "incoming": incomingTransactions,
    })

    return render_to_response("userprofile/profile.html", dictData,)
def statement(request, pk):
    dictData = baseDict(request)
    today = datetime.today().date()
    timeAgo = today - timedelta(days=30) # get transactions in the last 30 days
    outgoingTransaction = OutgoingTransaction.objects.filter(fromUser=request.user, fromAccount__pk=pk, theDate__gte = timeAgo)
    incomingTransaction = IncomingTransaction.objects.filter(toUser=request.user, toAccount__pk=pk, theDate__gte = timeAgo)

    dictData.update({
        'account' : Account.objects.get(owner=request.user, pk=pk),
        'outgoing' : outgoingTransaction,
        'incoming' : incomingTransaction,
    })

    return render_to_response("userprofile/statement.html", dictData)
def single_budget_view(request,pk): # that budget overview
    dictionary = baseDict(request)
    budget = MonthlyBudget.objects.get(pk=pk)
    purchases = Purchase.objects.filter(budget=budget)
    spent = 0
    for purchase in purchases:
        spent+=purchase.price
        
    dictionary.update({
        "budget":budget,
        "purchases" : purchases,
        "spent" : spent,
    })
    return render_to_response("budget/single_budget_view.html", dictionary)
def main(request):
    dictionary = baseDict(request) # get core data
    today = datetime.date.today()
    try: # might throw a non setup budget error
        currentMonthlyBudget = MonthlyBudget.objects.get(date__year=today.year, date__month=today.month, user=request.user)
        # fetch the current budget
        monthlyPurchaseList = Purchase.objects.filter(budget=currentMonthlyBudget)
        # fetch all items bought during that period
        totalSpentMonth = 0
        for purchase in monthlyPurchaseList:
            totalSpentMonth += purchase.price

        # this is the logic for creating the bar graph
        categoryPercent = [] # used to construct the counter
        spentPercent = []
        categories = Category.objects.filter(budget = currentMonthlyBudget)
        if currentMonthlyBudget.limit == 0:
            raise Exception('Division by zero !')
        for category in categories:
            categoryPercent.append(100 * category.price/currentMonthlyBudget.limit) # percentify the vlaues
            spentPercent.append(100 * category.spent/category.price)
        # bargraph logic ends here

        # get cat picture segment
        # get spent so far
        spent = 0
        purchases = Purchase.objects.filter(budget=currentMonthlyBudget)
        for purchase in purchases:
            spent += purchase.price

        monthLen = monthrange(datetime.datetime.today().year, datetime.datetime.today().month)[1] # get the length of current month (28,30,31 days)
        avgSpent = int(spent/datetime.datetime.today().day) # normalize, get average spent so far
        avgTotal = currentMonthlyBudget.limit / monthLen # get total monthly average

        ratio = int(avgSpent*avgTotal/100) # generate meme based on these values

        meme = get_meme_picture(ratio)

        dictionary.update({
            "currentBudget": currentMonthlyBudget,
            "purchases": monthlyPurchaseList,
            "total": totalSpentMonth,
            "date" : datetime.datetime.now().strftime("%B, %Y"),
            "categories": zip(Category.objects.filter(budget__user = request.user), categoryPercent, spentPercent ),
            "meme": meme,
        })
    except ObjectDoesNotExist:
        pass
    return render_to_response("budget/main.html", dictionary)
def changeSettings(request):
    dictData = baseDict(request)
    userData = get_object_or_404(BankingPerson, user=request.user)

    if request.method == 'POST':
        postData = request.POST
        form = UserSettingsForm(postData, instance=userData)

        if form.is_valid():
            form.save()
    else:
        form = UserSettingsForm(instance=userData)

    dictData.update({
        'form' : form,
    })

    return render_to_response("userprofile/forms/settingsForm.html", dictData,  context_instance=RequestContext(request))
def save_to_payee(request):
    dictionary = baseDict(request)

    if request.method == "POST":
        form = SavedPayeeForm(request.POST)
        if form.is_valid():
            payee = form.save(commit=False)
            payee.owner = request.user
            payee.save()
            dictionary.update({
                "message": "Added to payee list!",
            })
            return render_to_response("alert.html", dictionary)
    else:
        form = SavedPayeeForm()
    dictionary.update({
        "form" : form,
    })
    return render_to_response("payment/forms/saved_payee_form.html", dictionary, context_instance=RequestContext(request))
def sendMoney(request):

    dictData = baseDict(request)
    formError = [] # this string will send the template message about insufficient funds

    bankingPerson = dictData['bankingPerson']
    myAccounts = dictData['accounts']
    myPayeeList = SavedPayee.objects.filter(owner=request.user)
    if request.method == 'POST':
        # if the form has been submitted, validate it (if invalid,
        # all the valid fields before submission will remain)

        form = OutgoingTransactionForm(request.POST, accounts=myAccounts)
        # accounts and auto-fill are keys to arguments, they will be poped by the Transaction form in it's constructor
        if form.is_valid():
            transaction = form.save(commit = False)
        # to be removed transaction = form.save(commit=False)
        #  gets the data from the form as a transaction object (Transaction model in account.models)
            myAccount = Account.objects.get(owner__pk = bankingPerson.pk , accountNumber = form.cleaned_data['account'], owner = bankingPerson) # get the account that was submited in the drop down menu. Get will fail if not found and will throw error if more than one
            # same is done below, but it's more straight forward

            if (myAccount.amount + myAccount.overdraft) <= 0:  # Redundant check for spending more money than you have + your overdraft
                formError.append("Not enough cash to finish the transaction !")
            else: # if the account we want to send money to is fetched successful, we execute the model transfer function
                result = myAccount.transfer(name=transaction.toName,iban = transaction.toIban, sort = transaction.toSortCode, amount = transaction.amount, description = transaction.description)
                if result != 0:
                    formError.append("Check the details and try again !")
                else:

                    return redirect("index") # Maybe redirect somewhere else <- this is where everything went right
        else:
            formError.append("Please check name, sortcode or account number and try again. ")
    else: # that means there is no post data, so the form is generated from scratch
        form = OutgoingTransactionForm(accounts=myAccounts)

    dictData.update({
        'formError' : formError,
        'form': form,
        'payeeList': myPayeeList,
        'token': Token.objects.get(user=request.user),
    })

    return render_to_response('payment/forms/sendMoney_form.html', dictData, context_instance=RequestContext(request))
def budget_add_purchase(request): # add a new purhcase to budget
    today = datetime.date.today()
    dictionary = baseDict(request)
    budget = MonthlyBudget.objects.get(date__year=today.year, date__month=today.month, user=request.user) # get budget based on current date
    category_choices = Category.objects.filter(budget=budget) # get all categories you have added as options

    if request.method == 'POST':
        
        form = PurchaseForm(request.POST) # recreate a form with autofiled dropdown categories according to budget
        if form.is_valid():
            purchase = form.save(commit=False)
            purchase.budget = budget
            purchase.save()
            dictionary.update({
                "message" : "Product added !",
            })
            return render_to_response("alert.html",dictionary)
    else:
        form = PurchaseForm()
    dictionary.update({
        "form": form,
    })
    return render_to_response("budget/forms/new_purchase_form.html", dictionary, context_instance=RequestContext(request))
def monthly_budget_setup(request): # this handles the form that will create the new budget
    dictionary = baseDict(request)
    formError = []
    if request.method == "POST": # submitted post validation
        form = MonthlyBudgetForm(request.POST)
        if form.is_valid():
            monthlyBudget = form.save(commit=False)
            monthlyBudget.user = request.user

            monthlyBudget.save()
            dictionary.update({
                "message" : "Budget successfully added !",
            })
            return render_to_response("alert.html",dictionary)

    else:
        form = MonthlyBudgetForm()

    dictionary.update({
        "form" : form,
        "formError" : formError,
    })
    return render_to_response("budget/forms/monthly_budget_form.html", dictionary, context_instance=RequestContext(request))
def change_account_name(request, pk):
    account = Account.objects.get(pk=pk)
    formError = [] # an array of potential errors
    dictionary = baseDict(request)
    if request.method == "POST":
        form = AccountRenameForm(request.POST)
        if form.is_valid():
            dictionary.update({
                "message" : "Account successfully renamed !",
            })
            account.accountName = form.cleaned_data['accountName']
            account.save()
            return render_to_response("alert.html",dictionary)
        else:
            formError.append("Please enter a valid input !")
    else:
        form = AccountRenameForm(instance = account)

    dictionary.update({
        "form" : form,
        "accountId" : pk,
    })

    return render_to_response("userprofile/forms/change_account_name.html", dictionary, context_instance=RequestContext(request))
def help_main(request):
    dictionary = baseDict(request)

    staticQuestions = StaticQuestion.objects.all()
    dictionary.update({
        "staticQuestions" : staticQuestions
    })

    if request.method == "POST":
        form = FormQuestinForm(request.POST)
        if form.is_valid():
            form.save()
            dictionary.update({
                "message": "Question has been submitted !"
            })
            return render_to_response("alert.html", dictionary)
    else:
        form = FormQuestinForm()

    dictionary.update({
        "form" : form,
    })

    return render_to_response("help/main_help_page.html", dictionary, context_instance=RequestContext(request))
def create_wishlist_item(request):

    dictionary = baseDict(request)
    if request.method == 'POST':
        form = WishlistItemForm(request.POST)
        if form.is_valid():
            wishlist_item = form.save(commit=False)
            wishlist_item.user = request.user
            wishlist_item.save()
            wishlistItems = WishlistItem.objects.all()

            dictionary.update({
                "wishlistItems" : wishlistItems,
            })
            return render_to_response("budget/get_saved_money.html", dictionary)
        else:
            return HttpResponse("gello")
    else:
        form = WishlistItemForm()
    dictionary.update({
        "form" : form,
    })

    return render_to_response("budget/forms/create_wishlist_item.html", dictionary, context_instance=RequestContext(request))
def legal(request):
    dictionary = baseDict(request)
    return render_to_response("controller/legal.html", dictionary)
def all(request):
	myDict = baseDict(request)
	myDict.update({
		'messages' : Notification.objects.filter(to=request.user).order_by("-theDate")
	})
	return render_to_response("notification/messages.html", myDict)
def budgeting_info(request):
    dictionary = baseDict(request)
    return render_to_response("controller/budgeting_info.html", dictionary)
def branch_finder(request):
    dictionary = baseDict(request)
    return render_to_response("map_finder.html", dictionary)
def service(request, slug=None):
    dictionary = baseDict(request)
    service = Service.objects.get(slug=slug)

    dictionary.update({"service": service})
    return render_to_response("controller/service.html", dictionary)
def student_account(request):
    dictionary = baseDict(request)
    return render_to_response("controller/student_account.html", dictionary)
def graduate_account(request):
    dictionary = baseDict(request)
    return render_to_response("controller/graduate_account.html", dictionary)