import cv2
import time
import threading
import playsound
import numpy as np
import urllib.request
from threading import Thread
from datetime import datetime

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

#import zmq
#import base64


class Client():
	def __init__(self):

		self.url = 'http://192.168.43.31:8080/shot.jpg'

		# sound alarm filename
		self.filename = 'sound/Siren-SoundBible.com-1094437108.wav'

		# 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()


	def play_alarm(self):
			start = datetime.now()
			while True:
				sec = (datetime.now() - start).seconds	
				playsound.playsound(self.filename)
	
				if sec > 8:
					print('seconds------', sec)
					break
      
	def send(self, client_name, sender):

		self.cap = cv2.VideoCapture(0)
		self.sender = sender
		time.sleep(5)
		
		while True:
			try:
				if client_name == 'ipcam':
					self.frame=urllib.request.urlopen(self.url)
					self.frame=np.array(bytearray(self.frame.read()), dtype=np.uint8)
					self.frame=cv2.imdecode(self.frame, -1)
				else:
					_, self.frame = self.cap.read()
				
				#with self.lock:
				s = self.sender.send_image(client_name, cv2.resize(self.frame, (320, 240)))
		#		s = s.decode('ascii')

		#		if s == 'alarm':
	#				alarmThread = Thread(target=self.play_alarm)
	#				alarmThread.deamon = True
	#				alarmThread.start()
				
				#print(client_name)
				self.frame = cv2.resize(self.frame, (640, 480))
				
				with self.lock:
					self.outputFrame = self.frame.copy()
			
			except Exception as e:
				print('cam',str(e))
				continue


	def generate(self):
		# loop over frames from the output stream
		while True:
			# wait until the lock is acquired
			with self.lock:
				if self.outputFrame is None:
					continue
	 
				(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
		client1 = Client()
		client2 = Client()
		
		cam1 = imagezmq.ImageSender(connect_to="tcp://192.168.43.98:5555")
		ipcam = imagezmq.ImageSender(connect_to="tcp://15.206.166.198:5556")

		# start thread execution 
		t = Thread(target=client1.send, args=('cam1', cam1))
		t.daemon = True
		t.start()
		
		t2 = Thread(target=client2.send, args=('ipcam', ipcam))
		t2.daemon = True
		# t2.start()
		
		# 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(client1.generate(),
				mimetype = "multipart/x-mixed-replace; boundary=frame")

		# @app.route('/video_feed2')
		# def video_feed():
		# 	# return the response generated along with the specific media
		# 	return Response(client1.generate(),
		# 		mimetype = "multipart/x-mixed-replace; boundary=frame")
			
			
		# 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)

