import re
from datetime import datetime
from pathlib import Path

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader

from troggle.core.models.caves import Cave
from troggle.core.models.logbooks import LogbookEntry, writelogbook  # , PersonLogEntry

# from databaseReset import reinit_db # don't do this. databaseRest runs code *at import time*
from troggle.core.models.troggle import Expedition, Person, PersonExpedition

from troggle.core.utils import current_expo, COOKIE_SHORT_TIMEOUT, PUBLIC_LAPTOP_COOKIE_NAME, PUBLIC_LAPTOP_COOKIE_TEXT
from troggle.parsers.imports import (
    import_caves,
    import_drawingsfiles,
    import_logbooks,
    import_people,
    import_QMs,
    import_survex,
    import_surveyscans,
)

from .auth import login_required_if_public

"""Utility functions and code to serve the control panel and individual user's 
progress and task list (deprecated as we do not have individual user login).
"""

todo = """
- [Low priority] Fix Login page so that it produces the frontpage or
  redirects to the page which produced the login prompt requirement.
  
- Statement on login page that "essential cookies" are used when you login
  to the website.
"""

def public_laptop(request):
    """Just sets a cookie. Visit this web page from Crowley, Anathema, Aziraphale, Pulsifer etc.
    
    This hack to be replaced in due course by a proper call from a user saying whether they are using a shared machine or not.
    """
    response = HttpResponse(f"Cookie has been set on this machine, which now defines it as a public laptop. So the login cookie lifetimes will now be short:{COOKIE_SHORT_TIMEOUT/(60*60)} hour(s)")
    response.set_cookie(PUBLIC_LAPTOP_COOKIE_NAME, PUBLIC_LAPTOP_COOKIE_TEXT, max_age=COOKIE_SHORT_TIMEOUT)  # Cookie expires in 1 hour
    return response

def todos(request, module):
    """produces todo text from module
    We could automate this to find all those strings automatically
    """
    from troggle.core.forms import todo as forms
    from troggle.core.middleware import todo as middleware
    from troggle.core.models.caves import todo as modelcaves
    from troggle.core.models.logbooks import todo as modellogbooks
    from troggle.core.TESTS.tests import todo as tests
    from troggle.core.views.caves import todo as viewcaves
    from troggle.core.views.drawings import todo as viewdrawings
    from troggle.core.views.logbooks import todo as viewlogbooks
    from troggle.core.views.other import todo as viewother
    from troggle.core.views.scans import todo as viewscans
    from troggle.core.views.survex import todo as viewsurvex
    from troggle.core.views.uploads import todo as viewuploads
    from troggle.core.views.user_registration import todo as viewregister
    from troggle.core.views.wallets_edit import todo as viewwallets_edit
    from troggle.core.views.logbook_edit import todo as viewlogbook_edit
    from troggle.parsers.caves import todo as parserscaves
    from troggle.parsers.drawings import todo as parsersdrawings
    from troggle.parsers.locations import todo as parserslocations
    from troggle.parsers.logbooks import todo as parserslogbooks
    from troggle.parsers.people import todo as parserspeople
    from troggle.parsers.users import todo as parsersusers
    from troggle.parsers.survex import todo as parserssurvex
    from troggle.urls import todo as todourls

    tododict = {
        "tests": tests,
        "forms": forms,
        "middleware": middleware,
        "models/caves": modelcaves,
        "models/logbooks": modellogbooks,
        "views/caves": viewcaves,
        "views/drawings": viewdrawings,
        "views/logbooks": viewlogbooks,
        "views/other": todo,
        "views/scans": viewscans,
        "views/survex": viewsurvex,
        "views/uploads": viewuploads,
        "views/user_registration": viewregister,
        "views/wallets_edit": viewwallets_edit,
        "views/logbook_edit": viewlogbook_edit,
        "parsers/caves": parserscaves,
        "parsers/drawings": parsersdrawings,
        "parsers/locations": parserslocations,
        "parsers/logbooks": parserslogbooks,
        "parsers/people": parserspeople,
        "parsers/users": parsersusers,
        "parsers/survex": parserssurvex,
        "urls": todourls,
    }
    return render(request, "core/todos.html", {"tododict": tododict})


def troggle404(request):  # cannot get this to work. Handler404 in urls.py not right syntax
    """Custom 404 page to be used even when Debug=True
    https://blog.juanwolf.fr/posts/programming/how-to-create-404-page-django/
    """
    context = RequestContext(request)
    # context['caves'] = Cave.objects.all()
    return render(request, ("errors/generic.html", context.flatten()))


def frontpage(request):
    """never seen in common practice. Logon should redirect here when this is more useful"""

    if request.user.is_authenticated:
        return render(request, "login/tasks.html")

    expeditions = Expedition.objects.order_by("-year")
    logbookentry = LogbookEntry
    cave = Cave
    return render(request, "login/frontpage.html", locals())


@login_required_if_public
def controlpanel(request):
    """Admin requires expoadmin user logged on
    Mostly disabled apart from logbook export
    DANGEROUS, these import functions kill the ground under your feet !
    """
    jobs_completed = []

    if not request.user.is_superuser:  # expoadmin is both .is_staff and ._is_superuser
        return render(
            request,
            "controlPanel.html",
            {"error": ' - Needs "expoadmin" or superuser logon. \nLogout and login again.', 
            "year": current_expo()}
            
        )
    else:
        return render(
            request,
            "controlPanel.html",
            {"expeditions": Expedition.objects.all(), "year": current_expo()},
        )

def folk_export(request):
    """Recreates the folk.csv file from the database contents
    WORK IN PROGRESS JULY 2025
    """
    def deslugify(slug):
        deslug = slug.replace("-"," ",1).title()
        return deslug
        
    def real_surname(person):
        return deslugify(person.slug).replace(person.first_name,"").strip()
        
    expo = {}
    yearlist = range(1976, int(current_expo())+1)
    newfile = settings.EXPOWEB / 'folk' / 'new_folk.csv'
    
    with open(newfile, 'w') as f:
        f.write("Name,Lastname,Guest,VfHO member,Mugshot,Blurbfile")
        for y in yearlist:
            try:
                expo[y] = Expedition.objects.get(year=y)
            except:
                expo[y] = None
            f.write(f",{y}")
        f.write("\n")
        for person in Person.objects.all().order_by("last_name"):
            f.write(f"{person.input_name}")
            if person.nickname:
                f.write(f" ({person.nickname})")
            f.write(f",{person.input_surname}") 
            if person.is_guest:
                f.write(",1")
            else:
                f.write(",")
            if person.is_vfho:
                f.write(",1")
            else:
                f.write(",")                
            if person.mugshot:
                f.write(f",{person.mugshot.replace('/folk/','')}")
            else:
                f.write(",")           
            if person.blurbfile:
                f.write(f",{person.blurbfile.replace('/folk/','')}")
            else:
                f.write(",")           
                
            for y in yearlist:
                present = PersonExpedition.objects.filter(expedition=expo[y], person=person)
                if present.count() == 1:
                    if present[0].noncaver:
                        f.write(f",-1")
                    else:
                        f.write(f",1")
                else:
                    f.write(",")
            f.write("\n")
    return render(
        request, 
        "controlPanel.html", 
        {"expeditions": Expedition.objects.all(), 
        "jobs_completed": f"GENERATED  {str(newfile)} {datetime.now().strftime('%Y-%m-%d %H:%M')}"
        }
    )        
    
def exportlogbook(request, year=None):
    """Constructs, from the database, a complete HTML formatted logbook
    for the current year. Format available is now just HTML2005. 
    Other formats have been retired.

    There are no images stored in the database. However links to images work in the HTML text of a logbook entry.

    This function is the recipient of the POST action as the export form in the control panel (now disabled).
    """

    def lbeKey(lbe):
        """This function goes into a lexicographic sort function - but where?!"""
        return str(lbe.slug) # now that slugs are tripid such as 2023-07-30b

    if not request.method == "POST":
        return render(request, "controlPanel.html", {"expeditions": Expedition.objects.all(), "jobs_completed": ""})
    else:
        # print(f"Logbook export {request.POST}")

        year = request.POST["year"]
        filename = "logbook-new-format.html"

        writelogbook(year, filename)
        #response = HttpResponse(content_type="text/html")
        #response["Content-Disposition"] = "attachment; filename=" + filename
        completed = f'Logbook exported to <a href="/years/{filename}">{filename}</a>'

        return render(
            request, "controlPanel.html", {"expeditions": Expedition.objects.all(), "jobs_completed": [completed]}
        )
