from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
import json
import os
import OMRChecker.main as OMRChecker
import Barcode.barcodeDetector as barcodeDetector
from urllib.parse import unquote
import cv2
from urllib.request import Request, urlopen
import numpy as np
from django.views.decorators.csrf import csrf_exempt
import sys



@csrf_exempt
def index(request):
    testNumber = 300
    if request.POST.get('questionNumber'):
        testNumber = request.POST.get('questionNumber')

    req = Request(
        request.POST.get('sheets'),
        headers={'User-Agent': 'Mozilla/5.0'})
    arr = urlopen(req).read()
    # utils.getROI(inOMR, 'filename.jpg', noCropping=args["noCropping"])

    inOMR = cv2.imdecode(np.array(bytearray(arr), dtype=np.uint8), cv2.IMREAD_GRAYSCALE)


    barcodeInfo = barcodeDetector.detetcting(arr)

    rotateType = None
    if(barcodeInfo) :
        if(barcodeInfo.orientation == "DOWN") :
            rotateType = cv2.ROTATE_180
        if(barcodeInfo.orientation == "RIGHT") :
            rotateType = cv2.ROTATE_90_COUNTERCLOCKWISE
        if(barcodeInfo.orientation == "LEFT") :
            rotateType = cv2.ROTATE_90_CLOCKWISE
        if(rotateType) :
            inOMR = cv2.rotate(inOMR, rotateType)
    #     cv2.imwrite(os.path.dirname(os.path.realpath(__file__))+'/ddd.jpg', inOMR)
        sheets = [inOMR]
        args = {'noCropping': True, 'autoAlign': False, 'setLayout': False, 'input_dir': None, 'output_dir': 'outputs', 'template': None}

        if args['template']:
            args['template'] = OMRChecker.Template(args['template'])

        if args['input_dir'] is None:
            args['input_dir'] = ['inputs']

        OMRChecker.process_dir('inputs', '', args['template'], sheets , testNumber)
        response = OMRChecker.allReadResponse
        return HttpResponse(JsonResponse({'result':response[0],'barcodeInfo':barcodeInfo.data.decode("utf-8"),'status':'success'}))
#         return JsonResponse({'result':response[0],'barcodeInfo':barcodeInfo.data.decode("utf-8"),'status':'success'} , safe=False)
    else :
#         return JsonResponse({'status':'error','error_message':'barcode not detected!','error_number':1} , safe=False)
        return HttpResponse(JsonResponse({'status':'error','error_message':'barcode not detected!','error_number':1}))
