import base64
import os

import cv2
import numpy as np
from django.http import StreamingHttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .models import Doc

face_detector_path = 'serviceApp/haarcascade_frontalface_default.xml'
face_detector = cv2.CascadeClassifier(face_detector_path)

# Create your views here.
def download(request):
    return render(request,'docList.html',{'active_menu':'download'})


def platform(request):
    return render(request,'platForm.html',{'active_menu':'platform'})

def getDoc(request,id):
    doc = get_object_or_404(Doc,id=id)
    update_to,filename = str(doc.file.split('/'))
    filepath = '%s/media/%s/%s' % (os.getcwd(),update_to,filename)
    response = StreamingHttpResponse(read_file(filepath,512))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response

def read_file(file_name,size):
    with open(file_name,'rb') as f:
        while True:
            c = f.read(size)
            if c:
                yield c
            else:
                break

@csrf_exempt
def facedetect(request):
    result = {}
    if request.method == 'POST':
        if request.FILES['file'].get('image', None) is not None:
            img = read_image(stream = request.FILES['image'])
        else:
            result.update({
                "#faceNum":-1
            })
            return JsonResponse(result)

        if img.shape[2] == 3:
            img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

        values = face_detector.detectMultiScale(
            img,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30),
            falgs = cv2.CASCADE_SCALE_IMAGE
        )

        values = [
            (int(a),int(b),int(a+c),int(b+d))
            for (a,b,c,d) in values
        ]

        result.update({
            "#faceNum":len(values),
            "face":values,
        })
        return JsonResponse(result)


def read_image(stream = None):
    if stream is not None:
        data_temp = stream.read()
    img = np.asarray(bytearray(data_temp), dtype="uint8")
    img = cv2.imdecode(img,cv2.IMREAD_COLOR)
    return img

@csrf_exempt
def facedetectDemo(request):
    result = {}
    if request.method == 'POST':
        if request.FILES['file'].get('image', None) is not None:
            img = read_image(stream = request.FILES['file'])
        else:
            result.update({
                "#faceNum":-1
            })
            return JsonResponse(result)

        if img.shape[2] == 3:
            imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        else:
            imgGray = img

        values = face_detector.detectMultiScale(
            imgGray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30),
            falgs = cv2.CASCADE_SCALE_IMAGE
        )

        values = [
            (int(a),int(b),int(a+c),int(b+d))
            for (a,b,c,d) in values
        ]
        retval,buffer_img = cv2.imencode('.jpg',img)
        img64 = base64.b64encode(buffer_img)
        img64 = str(img64, 'utf-8')
        result['img64'] = img64
        return JsonResponse(result)