
import io
import numpy as np 
import time
import cv2
from google.cloud import vision
from google.cloud.vision import types
import requests
import json
from flask import Flask, render_template, Response

app = Flask(__name__)

class Camera():

    def __init__(self):
        self.client = vision.ImageAnnotatorClient()
        self.i_post_data = json.dumps({
            "to": "/topics/int",
            "notification": {
                "body": "Check your camera!",
                "title": "Intruder Detected",
                "sound": "default"
            }, 
        })
        self.s_post_data = json.dumps({
            "to": "/topics/int",
            "notification": {
                "body": "Check your camera!",
                "title": "Smoke/Fire Detected",
                "sound": "default"
            }, 
        })
        self.header_data = {
            'Authorization': 'key=AIzaSyDwT8sJsG6WVaLkOJgUMi0FQtK7d5YxA_0',
            'Content-type': 'application/json'
        }
        self.cam = cv2.VideoCapture(0)
        self.w = self.cam.get(cv2.CAP_PROP_FRAME_WIDTH)
        self.h = self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT)

    def streaming_annotate(self):
        t = 0
        s = 0
        a = 0
        while(True):
            ret, frame = self.cam.read()
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            frame_str = cv2.imencode('.jpg', frame)[1].tostring()

            if a % 20 != 0:
                yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_str + b'\r\n')

            if a % 20 == 0:
                image = types.Image(content=frame_str)
                objects = self.client.object_localization(image=image).localized_object_annotations[:3]
                labels = self.client.label_detection(image=image).label_annotations[:3]

                for label in labels:
                    if label.description == "Smoke" or label.description == "Fire":
                        if time.time() - s > 15:
                            s = time.time()
                            r = requests.post (
                                'https://fcm.googleapis.com/fcm/send', 
                                data = self.s_post_data, 
                                headers= self.header_data,
                            )
                            break
                for object_ in objects:
                    if object_.name == "Person" and object_.score > 0.60:
                        v1 = object_.bounding_poly.normalized_vertices[1]
                        v2 = object_.bounding_poly.normalized_vertices[3]

                        rect = cv2.rectangle(frame, (int(v1.x * self.w), int(v1.y * self.h)), (int(v2.x * self.w), int(v2.y * self.h)), (255,0,0), 2)
                        frame = cv2.addWeighted(frame, 1, rect, 1, 0)
                        
                        if time.time() - t > 15:
                            t = time.time() 
                            r = requests.post (
                                'https://fcm.googleapis.com/fcm/send', 
                                data = self.i_post_data, 
                                headers= self.header_data,
                            )

                frame_str = cv2.imencode('.jpg', frame)[1].tostring()
                yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_str + b'\r\n')

            a = a + 1

        self.cam.release()
        cv2.destroyAllWindows()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/video_feed/')
def video_feed():
    camera = Camera()
    return Response(camera.streaming_annotate(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='10.128.28.126')