# -*- coding: utf-8 -*-

from django.shortcuts import render, redirect
from students.models import Student, Group, Course
from django.http import HttpResponse
from forms import ContactForm
from django.views.generic import View
from django.core.mail import send_mail

#Простейшая view
def students_list(request):
    students = Student.objects.all()
    return render(request, 'students/list.html', {'students': students})

#view с принимаемым аргументом    
def students_item(request, student_id):
    students = Student.objects.get(id=student_id)
    return render(request, 'students/item.html', {'students': students})

########
#class-based views — описание view в виде класса   
def students_based(request, students, template):
    return render(request, 'students/'+template+'.html', {'students': students})

class Student_view(View):
    def get(self, request, student_id):
       
        if student_id != '0' : return students_based(request, Student.objects.get(id=student_id), 'item') 
        
        return students_based(request, Student.objects.all(), 'list') 

#Пример отправки почтового сообщения
def Smail(request):
    send_mail('Subject here', 'Here is the message.', 'any@any.com', ['any@any.com'], fail_silently=False)
    return HttpResponse("Сообщение отправлено!")

#Django ORM - механизм работы с базой без SQL    
def group_course_list(request, cg_id):
    #Выборка с условием по полю id
    course = Course.objects.get(id=cg_id)
    #Выборка всех записей
    studentsc = course.students.all()
    
    group = Group.objects.get(id=cg_id)
    studentsg = group.students.all()
    
    return render(request, 'students/glist.html', {'course': course , 
        'studentsc': studentsc, 'group': group , 'studentsg': studentsg})

#Два варианта view с формой POST (Закомментирован старый, громоздкий вариант)        
def form(request, student_id):
    student = Student.objects.get(id=student_id)
    
    #Если пришла POST форма
    if request.POST:
        #form = ContactForm(request.POST)
        form = ContactForm(request.POST, instance=student)
        
        #Проверка заполненности полей
        if form.is_valid():
            # cd = form.cleaned_data
            # student.name = cd['name']
            # student.surname = cd['surname']
            # student.date_of_birth = cd['date_of_birth']
            # student.email = cd['email']
            # student.phone = cd['phone']
            # student.save()
            student = form.save()

            return redirect(students_list)
    else:
        #form = ContactForm(initial={'name': student.name,'surname': student.surname,
        #    'date_of_birth': student.date_of_birth,'email': student.email,'phone': student.phone})
        form = ContactForm(instance=student)

    return render(request, 'students/form.html', {'form':form})
