#Pavol Debnar 
#Thesis 2022/23

#for use of this script, TCP_IP address must be changed and the folders in writeString and fileString

import socket
import cv2
import numpy as np
import os


def variance_of_laplacian(image):
	return cv2.Laplacian(image, cv2.CV_64F).var()



os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"]="rtsp_transport;tcp"

gstreamerstr = "tcpclientsrc host=192.168.1.110 port=5000 ! jpegdec ! videoconvert ! appsink"

def recvall(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf

TCP_IP = '192.168.1.2' #needs to be BBX-mini address
TCP_PORT = 5001

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(True)
conn, addr = s.accept()


#if not capture.isOpened() : print("CANNOT OPEN STREAM")
#capture = cv2.VideoCapture("vid.mp4")
keypressNo = 1
while(True):
    capture = cv2.VideoCapture(gstreamerstr,cv2.CAP_GSTREAMER)
    ret, frame = capture.read()
    if not ret:
        print('fail')
        break

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    variance = variance_of_laplacian(frame)

    cv2.putText(frame, "{}: {:.2f}".format("Variance:", variance), (10, 30),
		cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
    cv2.imshow('frame',frame)
    #cv2.waitKey(0)
    
   
    
    while(True):
        frames=[]
        maxVarIdx = 0
        maxVar = 0
        conn.send("n".encode())
    	length = conn.recv(3)
    	stringData = recvall(conn, int(length))
    	stringData=stringData.decode()
    	print(stringData)
    	maxVar=0
    	var=0
        for i in range(30):
            ret, frame = capture.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            frames.append(frame)
            cv2.imshow("frame",frame)
            var = variance_of_laplacian(frame)
            if var > maxVar:
                maxVar = var
                maxVarIdx = i

                conn.send("n".encode())
                length = conn.recv(3)
                stringData = recvall(conn, int(length))
                stringData=stringData.decode()
                print(stringData)

            cv2.waitKey(40)
            #test to see if the image with the highest variance gets picked
            #cv2.putText(frame, "{}: {:.2f}".format("Variance:", var), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
            #writeString="imgtest"+str(keypressNo)+"-"+str(i)+".jpg"
            #cv2.imwrite(writeString, frames[i])
        writeString="/home/palko/Documents/Documents/Diplomka/src/online/img"+str(keypressNo)+".png"
        fileString = "/home/palko/Documents/Documents/Diplomka/src/online/img" + str(keypressNo) + ".json"
        myfile = open(fileString, "w")
        a=myfile.write(stringData)
        myfile.close()
        cv2.imwrite(writeString, frames[maxVarIdx])
        keypressNo=keypressNo+1
        

capture.release()
cv2.destroyAllWindows()
