from django.shortcuts import render
from .models import PublicKey
from .form import AddPublicKeyForm
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
import json


@login_required(login_url='/account/login/')
def add_public_key(request):
    if request.method == 'POST':
        add_public_key_form = AddPublicKeyForm(data=request.POST)
        if add_public_key_form.is_valid():
            data = add_public_key_form.cleaned_data
            new_public_key = PublicKey()
            new_public_key.public_key = data['public_key']
            new_public_key.user = request.user
            # 保存
            new_public_key.save()
            response = ['public ket added']
            return HttpResponse(json.dumps(response))
        else:
            response = ['illegal input']
            return HttpResponse(json.dumps(response))
    # 用于测试
    # elif request.method == 'GET':
    #     user_register_form = UserRegisterForm()
    #     context = {'form': user_register_form}
    #     return render(request, 'register.html', context)
    else:
        response = ['illegal method, please use post']
        return HttpResponse(json.dumps(response))


@login_required(login_url='/account/login/')
def get_public_key(request):
    if request.method == 'POST':
        add_public_key_form = AddPublicKeyForm(data=request.POST)
        if add_public_key_form.is_valid():
            data = add_public_key_form.cleaned_data
            new_public_key = PublicKey()
            new_public_key.public_key = data['public_key']
            new_public_key.user = request.user
            # 保存
            new_public_key.save()
            response = ['public ket added']
            return HttpResponse(json.dumps(response))
        else:
            response = ['illegal input']
            return HttpResponse(json.dumps(response))
    # 用于测试
    # elif request.method == 'GET':
    #     user_register_form = UserRegisterForm()
    #     context = {'form': user_register_form}
    #     return render(request, 'register.html', context)
    else:
        response = ['illegal method, please use post']
        return HttpResponse(json.dumps(response))