import cv2
import time
import threading
from threading import Thread

import cv2
from imagezmq import imagezmq
 
from flask import Flask, render_template, Response

class Client():
	def __init__(self):

		# initialize the ImageSender object with the socket address of the
		self.sender = imagezmq.ImageSender(connect_to="tcp://192.168.43.98:5555")
		self.cap = cv2.VideoCapture(0)


	def send(self):
 		
 		# initialize the output frame and a lock used to ensure thread-safe
		# exchanges of the output frames (useful when multiple browsers/tabs
		# are viewing the stream)
		self.outputFrame = None
		self.lock = threading.Lock()
		time.sleep(5)

		while True:
			# read the frame from the camera and send it to the server
			_, frame = self.cap.read()
			frame = cv2.resize(frame, (640, 480))
			self.sender.send_image('+918980385272', cv2.resize(frame, (320, 240)))
			with self.lock:
				self.outputFrame = frame.copy()


	def generate(self):
		# loop over frames from the output stream
		while True:
			# wait until the lock is acquired
			with self.lock:
				# check if the output frame is available, otherwise skip
				# the iteration of the loop
				if self.outputFrame is None:
					continue
	 
				# encode the frame in JPEG format
				(flag, enc_image) = cv2.imencode(".jpg", self.outputFrame)
				# ensure the frame was successfully encoded
				if not flag:
					continue
	 
			# yield the output frame
			yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + 
				bytearray(enc_image) + b'\r\n')


if __name__ == '__main__':

	try:

		# initialize main object
		client = Client()
		
		# initialize a flask app 
		app = Flask(__name__)

		@app.route("/")
		def index():
			# return the rendered template
			return render_template("index.html")

		@app.route("/video_feed")
		def video_feed():
			# return the response generated along with the specific media
			return Response(client.generate(),
				mimetype = "multipart/x-mixed-replace; boundary=frame")
			
		
		# start thread execution 
		t = Thread(target=client.cam1)
		t.daemon = True
		t.start()

	 	t2 = Thread(target=client.ipcam)
		t2.daemon = True
		t2.start()
		
		# start the app
		app.run(host='0.0.0.0', port=8001, debug=True,
			threaded=True, use_reloader=False)

	except KeyboardInterrupt:
		try:
			sys.exit(0)
		except SystemExit:
			os._exit(0)
