# -*- coding: utf-8 -*-
"""
Created on Mon Jan 20 13:11:39 2020

@author: Rishabh
"""
import requests

final_list = []
def notifyServer(number):
    
    requests.post('http://localhost:3000/validateNumber',data={'number':number})



def main(image):
    global final_list

    blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()         # attempt KNN training

    if blnKNNTrainingSuccessful == False:                               # if KNN training was not successful
        #print("\nerror: KNN traning was not successful\n")  # show error message
        return                                                          # and exit program
    # end if

    imgOriginalScene  = image              # open image

    #if imgOriginalScene is None:                            # if image was not read successfully
     #   print("\nerror: image not read from file \n\n")  # print error message to std out
      #  os.system("pause")                                  # pause so user can see error message
       # return                                              # and exit program
    # end if


    listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)           # detect plates

    listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)        # detect chars in plates

#    cv2.imshow("imgOriginalScene", imgOriginalScene)            # show scene image

    if len(listOfPossiblePlates) == 0:                          # if no plates were found
        print("\nno license plates were detected\n")  # inform user no plates were found
    else:                                                       # else
                # if we get in here list of possible plates has at leat one plate

                # sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
        listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)

                # suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
        licPlate = listOfPossiblePlates[0]

#        cv2.imshow("imgPlate", licPlate.imgPlate)
        cv2.imwrite('01.png',licPlate.imgPlate)
           # show crop of plate and threshold of plate
#        cv2.imshow("imgThresh", licPlate.imgThresh)

        if len(licPlate.strChars) == 0:                     # if no chars were found in the plate
            #print("\nno characters were detected\n\n")  # show message
            return                                          # and exit program
        # end if

        drawRedRectangleAroundPlate(imgOriginalScene, licPlate)             # draw red rectangle around plate

       # print("\nlicense plate read from image = " + licPlate.strChars + "\n")  # write license plate text to std out
       # print("----------------------------------------")
        csvFile = open('npaaa.csv', 'a')
        csvWriter = csv.writer(csvFile)
        csvWriter.writerow(licPlate.strChars)
        



        writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)           # write license plate text on the image

#        cv2.imshow("imgOriginalScene", imgOriginalScene)                # re-show scene image

#        cv2.imwrite("imgOriginalScene.png", imgOriginalScene)           # write image out to file

    # end if else

       # cv2.waitKey(0)					# hold windows open until user presses a key
               ################# PRINT STATEMENT ###############
        pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract'

        o = str(pytesseract.image_to_string(Image.open('01.png')))
        #print(o)
        final_list.append(o)


    return
# end main

###################################################################################################
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):

    p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene)            # get 4 vertices of rotated rect

    cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_RED, 2)         # draw 4 red lines
    cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), SCALAR_RED, 2)
    cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), SCALAR_RED, 2)
    cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), SCALAR_RED, 2)
# end function

###################################################################################################
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
    ptCenterOfTextAreaX = 0                             # this will be the center of the area the text will be written to
    ptCenterOfTextAreaY = 0

    ptLowerLeftTextOriginX = 0                          # this will be the bottom left of the area that the text will be written to
    ptLowerLeftTextOriginY = 0

    sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape
    plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape

    intFontFace = cv2.FONT_HERSHEY_SIMPLEX                      # choose a plain jane font
    fltFontScale = float(plateHeight) / 30.0                    # base font scale on height of plate area
    intFontThickness = int(round(fltFontScale * 1.5))           # base font thickness on font scale

    textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale, intFontThickness)        # call getTextSize

            # unpack roatated rect into center point, width and height, and angle
    ( (intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) = licPlate.rrLocationOfPlateInScene

    intPlateCenterX = int(intPlateCenterX)              # make sure center is an integer
    intPlateCenterY = int(intPlateCenterY)

    ptCenterOfTextAreaX = int(intPlateCenterX)         # the horizontal location of the text area is the same as the plate

    if intPlateCenterY < (sceneHeight * 0.75):                                                  # if the license plate is in the upper 3/4 of the image
        ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6))      # write the chars in below the plate
    else:                                                                                       # else if the license plate is in the lower 1/4 of the image
        ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(round(plateHeight * 1.6))      # write the chars in above the plate
    # end if

    textSizeWidth, textSizeHeight = textSize                # unpack text size width and height

    ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth / 2))           # calculate the lower left origin of the text area
    ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight / 2))          # based on the text area center, width, and height

            # write the text on the image
    cv2.putText(imgOriginalScene, licPlate.strChars, (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace, fltFontScale, SCALAR_YELLOW, intFontThickness)
# end function

###################################################################################################
if __name__ == "__main__":
    # Main.py
    import csv
    
    import cv2
    import numpy as np
    import os
    
    import DetectChars
    import DetectPlates
    import PossiblePlate
    
    from PIL import Image
    import pytesseract
    import glob
    

    
    # module level variables ##########################################################################
    SCALAR_BLACK = (0.0, 0.0, 0.0)
    SCALAR_WHITE = (255.0, 255.0, 255.0)
    SCALAR_YELLOW = (0.0, 255.0, 255.0)
    SCALAR_GREEN = (0.0, 255.0, 0.0)
    SCALAR_RED = (0.0, 0.0, 255.0)
    
    showSteps = False    

    vidcap = cv2.VideoCapture('t10.mp4')
    def getFrame(sec):
        vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
        hasFrames,image = vidcap.read()
        name="daa\ "+str(sec)+".jpg"
        if hasFrames:
            cv2.imwrite(name, image)     # save frame as JPG file
        return hasFrames
    sec = 0
    frameRate = 0.5
    success = getFrame(sec)
    while success:
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec)


    images = [cv2.imread(file) for file in glob.glob("daa\*.jpg")]
    for image in images:
        main(image)
    final_result = []
    for plate in final_list:
        edited_plate = ''.join(plate.split())
        if len(edited_plate) == 10:
            final_result.append(edited_plate)


    l1 = []
    l3=[]
    for i in final_list:
        for j in i:
                if ord(j)>=65 and ord(j)<=97 or ord(j)>=48 and ord(j)<=57 or ord(j)>=97 and ord(j)<=122:
                    l1.append(j)
        l3.append(''.join(l1))
        l1=[]
        
    frame_num = 0   
    for i in l3:
        if len(i) == 10:
            print("*****************************")
            print("Extracted License Number is: {}".format(i))
            print("The Frame from which license number is extracted is: {}".format(frame_num))
            notifyServer(i)
        frame_num += 0.5


        
        
        
        