from bz2 import compress
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
import mimetypes
import os
from pathlib import Path, PureWindowsPath

from io import BytesIO
import zipfile

from django.core.exceptions import ValidationError
from .validators import validate_statistic_input
from .validators import validate_download_input

FOLDER_PATH = Path.cwd().parents[0] / "textfiles"
OUTPUT_PATH = FOLDER_PATH / "output"
# OUTPUT_PATH = Path.cwd().parents[2] / "output"


@login_required
def output_view(request):
    return render(request, "output/base.html")

def create_zip(files_list: list):
    # zip_filename = "output.zip"
    in_memory = BytesIO()

    compressor = zipfile.ZipFile(in_memory, "w")

    print(type(compressor))

    for file in files_list:
        compressor.write(OUTPUT_PATH / file, file)
    compressor.close()

    return in_memory

@login_required
def download_data(request):
    if request.method == "GET":
        request_data = request.GET
        try:
            validate_download_input(request_data)
        except ValidationError:
            return HttpResponse("Corrupt request", status=400)

        if len(request_data) == 0:
            return JsonResponse({}, status=204)

        requested_files = []

        for data in request_data.keys():
            if data == "results_plain":
                requested_files.append("read_spikes.txt")
            elif data == "results_binary":
                requested_files.append("spikes.bin")
            elif data == "metric_pr":
                requested_files.append("pr_output.txt")
            elif data == "metric_cv":
                requested_files.append("cv_output.txt")
            elif data == "metric_pc":
                requested_files.append("pc_output.txt")
            
        zip_file = create_zip(requested_files)

        resp = HttpResponse(zip_file.getvalue(), content_type = "application/x-zip-compressed", status= 200)
        resp["Content-Disposition"] = "attachment; filename=%s" % "output.zip"

        return resp
    return HttpResponse("Wrong method", status=405)

@login_required
def get_statistics(request):

    res = {};

    if request.method == "GET":
        stats = request.GET
        validate_statistic_input(stats)
        for element in stats.keys():
            if element == "PC":
                filename = OUTPUT_PATH / "pc_output.txt"
            elif element == "PR":
                filename = OUTPUT_PATH / "pr_output.txt"
            elif element == "CV":
                filename = OUTPUT_PATH / "cv_output.txt"
            else:
                raise ValueError("Not a statistic")

            with open(filename , "r") as file:
                data = file.read()
            res[element] = data
        return JsonResponse(res)
    return HttpResponse("wrong method", status=405)

"""
def get_spike_files():
    spike_files = []
    output_path = FOLDER_PATH / "output"
    if not output_path.is_dir():
        raise ValueError("{} is not a folder.".format(str(output_path)))    #XXX Better exception
    for file in output_path.iterdir():
        if "read_spikes_node" in file.name:
            spike_files.append(file.name)
    
    return spike_files

def get_downloadable_files():
    file_name_list = []

    output_path = FOLDER_PATH / "output"
    for file in output_path.iterdir():
        if (file.name.startswith("read_spikes") and not file.name.endswith(".bin")) or "output" in file.name or file.name.startswith("spikes"):
            file_name_list.append(file.name)

    print(file_name_list)"""