#coding=utf-8


import time
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.shortcuts import render
from django.contrib.auth import login as auth_login



def my_login(request, template_name, authentication_form, *args, **kwargs):
    next = request.GET.get('next')

    if request.method == 'POST':
        form = authentication_form(data=request.POST, request=request)
        if form.is_valid():
            user = form.get_user()
            auth_login(request, user)

            if next:
                return HttpResponseRedirect(next)
            else:
                return HttpResponseRedirect('/')
        else:
            time.sleep(3)
            # if request.POST['username'] != 'zzzroor':
            #     BizLog.objects.addnew(None, BizLog.INSERT, u"[%s]登录失败,密码[%s],IP[%s]" % (
            #         request.POST['username'],
            #         request.POST['password'],
            #         request.META['REMOTE_ADDR']
            #     ))
    else:
        form = authentication_form()

    return render(request, template_name, {'form':form, 'next':next})

def my_logout(request, *args, **kwargs):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    return HttpResponseRedirect('/')




def index(request):
    user_id = request.META.get('HTTP_USER_ID')
    token = request.META.get('HTTP_ACCESS_TOKEN')
    if not user_id or not token:
        return HttpResponseRedirect('/views/account/login.html')
    else:
        return HttpResponsePermanentRedirect("/views/index.html")

@login_required
def home(request, template_name):
    return render(request, template_name)