from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms.models import model_to_dict

from addentry.models import Entry, Meaning
from django.db.models.query import QuerySet

from .forms import SearchForm

# Create your views here.


# index.html-in-chief. as a search tool.

# return Gaeilge search result
def ga_search(request, entry=""):

    search_form = SearchForm(initial={'choice_field': 'Gaeilge'})

    if request.method == "POST":
        regForm = SearchForm(request.POST)
        if regForm.is_valid():
            option = regForm.cleaned_data['choice_field']
            search_content = regForm.cleaned_data["search_content"]

            if option == 'Gaeilge':
                return redirect("ga_search", entry=search_content)
        
            if option == 'Explanation':
                # TODO
                return HttpResponse("TODO")

    entry_list = Entry.objects.filter(Gaeilge=entry)
    entry_id_list= list(map(lambda x : x.id, entry_list))
    meaning_result_list = list(map(lambda x : Meaning.objects.filter(Entry=x), entry_id_list))

    # 攤平例句
    def flatten_sentence(e):
        result = e.Meaning_content
        if e.Exam_Sentence1 != None:
            result += (" " + e.Exam_Sentence1 + " " + e.Exam_Sentence1_zh)
        if e.Exam_Sentence2 != None:
            result += (" "  + e.Exam_Sentence2 + " " +e.Exam_Sentence2_zh)
        if e.Exam_Sentence3 != None:
            result += (" "  + e.Exam_Sentence3 + " " + e.Exam_Sentence3_zh)
        return result


    # 將函數作用到 QuerySet 和 List 的樹的每個元素
    def tree_mapping(func, tree):
        from django.db.models.query import QuerySet
        if isinstance(tree, QuerySet) or isinstance(tree, list):
            if isinstance(tree, QuerySet):
                tree = list(tree)
                
            result = []
            for i in tree:
                result.append(tree_mapping(func,i))
            return result
        else:
            return func(tree)

    '''# 攤平眾釋義成一個例句
    def flatten_meanings(item):
        pass'''
    
    # [['word1 meaning1'], ['word2 meaning1', 'word2 meaning2'], ...]
    meaning_result_list_sent_flattened = tree_mapping(flatten_sentence, meaning_result_list)

    entry_dict_list = list(map(model_to_dict, entry_list))

    for i in range(len(entry_dict_list)):
        entry_dict_list[i]['Explanation'] = meaning_result_list_sent_flattened[i]

    ''' keys of entry_dict :
    id (int), Gaeilge, POS, Pronoun, PreScript, Pronoun, PostScript, Explanation (a list)

    '''

    context = {
        'entry' : entry,
        'form' : search_form,
        'entry_len' : len(entry_dict_list),
        'entry_list' : entry_dict_list
        }
    #return HttpResponse(meaning_result_list_sent_flattened.__str__)
    return render(request, 'ga_search.html', context)