from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from datetime import datetime
from .add_entry_form import EntryForm, MeaningForm
from .models import Entry, Meaning
from django.forms import formset_factory


# Create your views here.
'''def hello_world(request):
    return render(request, 'hello_world.html',
    {'current_time' : str(datetime.now()),})'''

@login_required #登入必要
def add_entry(request):
    
    # it becomes true when stored successfully
    is_saved = False

    if request.method == "POST":
        entry_form = EntryForm(request.POST)
        if entry_form.is_valid:
            entry_form.save()


            latest_entry_id = Entry.objects.latest('id').id
            MeaningFormSet = formset_factory(MeaningForm, extra=5)
            meaning_form_set = MeaningFormSet(data=request.POST or None)
            
            meaning_form_valid_length = len(list(filter(lambda x : x == {} , meaning_form_set.errors)))

            i = 0
            for form in meaning_form_set:
                if i < meaning_form_valid_length:
                    form.save()
                    raise Exception("Form Saved!")
                    i += 1
                else:
                    break

            latest_meaning_id = Meaning.objects.latest('id').id

            # update the entry id of meaning
            valid_meaning_list = Meaning.objects.all().order_by('-id')[:meaning_form_valid_length]
            for meaning in valid_meaning_list:
                Meaning.objects.filter(id=meaning.id).update(Entry=latest_entry_id)

            is_saved = True
    
    entry_list = list(Entry.objects.all())[-10:]
    meaning_list = list(Meaning.objects.all())[-20:]



    
    entry_form = EntryForm()
    meaning_form_set = formset_factory(MeaningForm, extra=5)

    context = {
        'is_saved' : is_saved,
        'entry_form' : entry_form,
        'meaning_form_set' : meaning_form_set,
        'entry_list' : entry_list,
        'meaning_list' : meaning_list,

    }
    

    return render(request, 'addentry/add_entry.html', context)


