# -*- coding: utf-8 -*-
# courses.p064.views

from django.http import HttpResponseRedirect

from courses.views import r2r, course_defaults
from courses.models import CourseSite, SecureCourseFile
from courses.forms import SearchForm, LoadScheduleForm
from people.funcs import is_faculty
from djphys.epoch import Epoch
from django.conf import settings
from pathlib import Path
import re


#def class_defaults(request):
#dic = {'course': CourseSite.objects.get(course__order_field='p064')}
#dic['epoch'] = Epoch().deserialize(request.session['epoch'])
#dic['calendar'] = dic['course'].calendar(request)
#dic['course_rec'] = dic['course'].course_record(dic['epoch'])
#dic['request'] = request
#if is_faculty(request.user):
#dic['loadform'] = LoadScheduleForm()
#return dic


def pages(request):
    dic = class_defaults(request)
    dic['searchresults'] = ""
    if request.method == 'POST':
        searchform = SearchForm(request.POST)
        if searchform.is_valid():
            terms = searchform.cleaned_data['terms']
            dic['searchresults'] = look_for(terms)
    else:
        searchform = SearchForm()
    dic['searchform'] = searchform
    return r2r(request, 'courses/p064pages.html', dic)


def search(request, dic):
    dic['searchresults'] = ""
    dic['URL'] = settings.P064URL
    if request.method == 'GET':
        searchform = SearchForm(request.GET)
        if searchform.is_valid():
            terms = searchform.cleaned_data['terms']
            hits = look_for(terms) # a set of the form file,term
            # We should make a button for each file
            counts = dict()
            for entry in hits:
                file, term = entry.split(',')
                if file not in counts:
                    counts[file] = term
                else:
                    counts[file] += ";" + term
            dic['buttons'] = counts
        else:
            searchform = SearchForm()

        dic['searchform'] = searchform

    return r2r(request, 'courses/p064search.html', dic)


def project(request):
    dic = course_defaults(request)
    return r2r(request, 'courses/p064project.html', dic)


def look_for(terms):
    """
    Perform a search through the .html files in
    the directory specified in the settings field P064FILES.
    To get the search terms noticed, when will need to install them
    in an in-document javascript variable.
    """
    dir = Path(settings.P064FILES)
    hits = set()
    # What patterns are we looking for?
    patterns = []
    if '"' in terms:
        copy = f"{terms}"
        for m in re.finditer(r'"(.*?)"', copy):
            patterns.append(re.compile(m.group(1), re.M))
            # remove from individual words
            terms = terms.replace(m.group(), "")
    for t in terms.strip().split(' '):
        if len(t):
            patterns.append(re.compile(t, re.M | re.I))

    for file in sorted(dir.glob('*.html')):
        # rewrite(file, "")
        try:
            txt = open(file, 'rb').read().decode('utf8')
        except Exception as eeps:
            print(eeps)
        for p in patterns:
            # Make sure we start the search after the menu stuff
            try:
                n = max(0, txt.find('<!-- menu-end -->'))
            except Exception as eeps:
                print(eeps)
                n = 0
            m = p.search(txt[n:])
            if m:
                hits.add(file.name + ',' + m.group())

        # mat = ";".join(hits)
        # rewrite(file, mat)
    return hits


def clear_search():
    dir = Path(settings.P064FILES)
    for file in dir.glob('*.html'):
        rewrite(file, "")


def rewrite(file, search_terms):
    ss = f'var search_terms = "{search_terms}";'
    txt = re.sub(r'<script id="search">(.*)?</script>',
                 f'<script id="search">{ss}</script>',
                 open(file, 'r').read(), re.M | re.DOTALL)
    open(file, 'w').write(txt)
