#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  	appCam.py
#  	based on tutorial ==> https://blog.miguelgrinberg.com/post/video-streaming-with-flask
# 	PiCam Local Web Server with Flask
# MJRoBot.org 19Jan18

from flask import Flask, render_template, Response, request

# Raspberry Pi camera module (requires picamera package)
from camera_pi import Camera

import config

app = Flask(__name__)

def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/view', methods=['GET', 'POST'])
def androidview():
    if request.form['intercom_id'] == config.getIntercomID():
        """Video streaming android home page."""
        return render_template('html5video.html')
    else:
        return "Please first link intercom to your android app to view the video feed"

if __name__ == '__main__':
    app.run(host=config.getIP(), port =config.getVideoPort(), debug=True, threaded=True)
