# -*-  coding:utf-8   -*-
from django.contrib.auth.models import User, send_mail
from models import ActivateCode, UserProfile
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.http import HttpResponse
import uuid, datetime
import os
from forum.settings import STORAGE_PATH, USERRES_URLBASE
from django.contrib.auth.decorators import login_required


def register(request):
    error = ''
    if request.method == "GET":
        return render_to_response("usercenter_register.html", {}, context_instance=RequestContext(request))
    else:
        username = request.POST['username'].strip()
        email = request.POST['email'].strip()
        password = request.POST['password'].strip()
        re_password = request.POST['re_password'].strip()
        if not username or not password or not email:
            error = u'任何字段都不能为空'
        if password != re_password:
            error = u'两次密码不一致'
        if User.objects.filter(username=username).count() > 0:
            error = u'用户名已存在'
        if not error:
            user = User.objects.create_user(username=username, email=email, password=password)
            user.is_active = False
            user.save()

            new_code = str(uuid.uuid4()).replace('-', '')
            expire_time = datetime.datetime.now() + datetime.timedelta(days=2)
            code_record = ActivateCode(owner=user, expire_timestamp=expire_time, code=new_code)
            code_record.save()

            activate_link = "http://%s%s" % (request.get_host(), reverse("usercenter_activate", args=[new_code]))
            send_mail(u'[Python部落论坛]激活邮件', u'您的激活码链接为:%s' % activate_link, 'test505305586@163.com',
                      [email], fail_silently=False)
        else:
            return render_to_response("usercenter_register.html", {"error": error},
                                      context_instance=RequestContext(request))

        return redirect(reverse("login"))


def activate(request, code):
    query = ActivateCode.objects.filter(code=code, expire_timestamp__gte=datetime.datetime.now())
    if query.count > 0:
        code_record = query[0]
        code_record.owner.is_activate = True
        code_record.owner.save()
        return HttpResponse(u'激活成功')
    else:
        return HttpResponse(u'激活失败')


@login_required
def upload_avatar(request):
    if request.method == 'POST':
        avatar_file = request.FILES.get("avatar", None)
        avatar_name = '{}{}'.format(request.user, avatar_file.name)

        file_path = os.path.join(STORAGE_PATH, avatar_name)
        with open(file_path, 'wb+') as destination:
            for chunk in avatar_file.chunks():
                destination.write(chunk)
        profile = UserProfile.objects.get(owner=request.user)
        profile.avatar = "%s/avatar/%s" % (USERRES_URLBASE, avatar_name)
        profile.save()
    else:
        profile = UserProfile.objects.get(owner=request.user)

    return render_to_response("usercenter_avatar.html", {"profile": profile}, context_instance=RequestContext(request))
