import os, stat
import re
import urllib.request, urllib.parse, urllib.error

from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404

from troggle.core.models_survex import ScansFolder, SingleScan, SurvexBlock, TunnelFile
from troggle.flatpages import views as flatviews
import parsers.surveys



def fa_readFile(*path):
    try:
        f = open(os.path.join(settings.FILES, *path))
    except:
        f = urllib.request.urlopen(settings.FILES+"download/")
    return f.read()
    
def upload(request, path):
    pass

def download(request, path):
    #try:
        
        return HttpResponse(fa_readFile(path), content_type=flatviews.getmimetype(path))
    #except:
    #    raise Http404

def UniqueFile(fname):
    while True:
        if not os.path.exists(fname):
            break
        mname = re.match("(.*?)(?:-(\d+))?\.(png|jpg|jpeg)$(?i)", fname)
        if mname:
            fname = "%s-%d.%s" % (mname.group(1), int(mname.group(2) or "0") + 1, mname.group(3))
    return fname


# join it all up and then split them off for the directories that don't exist
# anyway, this mkdir doesn't work
def SaveImageInDir(name, imgdir, project, fdata, bbinary):
    print(("hihihihi", fdata, settings.SURVEYS))
    fimgdir = os.path.join(settings.SURVEYS, imgdir)
    if not os.path.isdir(fimgdir):
        print("*** Making directory", fimgdir)
        os.path.mkdir(fimgdir)
    fprojdir = os.path.join(fimgdir, project)
    if not os.path.isdir(fprojdir):
        print("*** Making directory", fprojdir)
        os.path.mkdir(fprojdir)
        print("hhh")
        
    fname = os.path.join(fprojdir, name)
    print(fname, "fff")
    fname = UniqueFile(fname)
    
    p2, p1 = os.path.split(fname)
    p3, p2 = os.path.split(p2)
    p4, p3 = os.path.split(p3)
    res = os.path.join(p3, p2, p1)
    
    print("saving file", fname)
    fout = open(fname, (bbinary and "wb" or "w"))
    fout.write(fdata.read())
    fout.close()
    res = os.path.join(imgdir, name)
    return res.replace("\\", "/")

def surveyscansfolder(request, path):
    #print [ s.walletname  for s in ScansFolder.objects.all() ]
    scansfolder = ScansFolder.objects.get(walletname=urllib.parse.unquote(path))
    return render_to_response('scansfolder.html', { 'scansfolder':scansfolder, 'settings': settings })

def surveyscansingle(request, path, file):
    scansfolder = ScansFolder.objects.get(walletname=urllib.parse.unquote(path))
    singlescan = SingleScan.objects.get(scansfolder=scansfolder, name=file)
    print("SSS {} {} :{}:".format(path, file, flatviews.getmimetype(file)))
    return HttpResponse(content=open(singlescan.ffile,"rb"), content_type=flatviews.getmimetype(file))
    #return render_to_response('scansfolder.html', { 'scansfolder':scansfolder, 'settings': settings })

def expofilessingle(request, filepath):
    # defaults to content_type="text/pain" needs fixing for PDFs
    fn=urllib.parse.unquote(filepath)
    return HttpResponse(content=open(settings.EXPOFILES+fn,"rb"))

def cssfilessingle(request, filepath):
    fn=urllib.parse.unquote(filepath)
    return HttpResponse(content=open(settings.MEDIA_ROOT+fn,"r"),content_type="text/css")

def surveyscansfolders(request):
    manyscansfolders = ScansFolder.objects.all()
    return render_to_response('manyscansfolders.html', { 'manyscansfolders':manyscansfolders, 'settings': settings })
    
    
def tunneldata(request):
    tunnelfiles = TunnelFile.objects.all()
    return render_to_response('tunnelfiles.html', { 'tunnelfiles':tunnelfiles, 'settings': settings })
    

def tunnelfile(request, path):
    tunnelfile = TunnelFile.objects.get(tunnelpath=urllib.parse.unquote(path))
    tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath)
    return HttpResponse(content=open(tfile), content_type="text/plain")
    
def tunnelfileupload(request, path):
    tunnelfile = TunnelFile.objects.get(tunnelpath=urllib.parse.unquote(path))
    tfile = os.path.join(settings.TUNNEL_DATA, tunnelfile.tunnelpath)
    
    project, user, password, tunnelversion = request.POST["tunnelproject"], request.POST["tunneluser"], request.POST["tunnelpassword"], request.POST["tunnelversion"]
    print((project, user, tunnelversion))
    
    
    assert len(list(request.FILES.values())) == 1, "only one file to upload"
    
    uploadedfile = list(request.FILES.values())[0]
        
    if uploadedfile.field_name != "sketch":
        return HttpResponse(content="Error: non-sketch file uploaded", content_type="text/plain")
    if uploadedfile.content_type != "text/plain":
        return HttpResponse(content="Error: non-plain content type", content_type="text/plain")
        
    # could use this to add new files
    if os.path.split(path)[1] != uploadedfile.name:  
        return HttpResponse(content="Error: name disagrees", content_type="text/plain")
    
    orgsize = tunnelfile.filesize   # = os.stat(tfile)[stat.ST_SIZE]
        
    ttext = uploadedfile.read()
    
    # could check that the user and projects agree here
    
    fout = open(tfile, "w")
    fout.write(ttext)
    fout.close()
    
    # redo its settings of 
    parsers.surveys.SetTunnelfileInfo(tunnelfile)
    tunnelfile.save()
    
    uploadedfile.close()
    message = "File size %d overwritten with size %d" % (orgsize, tunnelfile.filesize)
    return HttpResponse(content=message, content_type="text/plain")

    
    

