#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''REST API for IP camera related operations'''

# System modules
from flask import Response, render_template, make_response, request
from flask_restx import Namespace, Resource, fields
from astropy.time import Time
import time

# Custom modules
import devices

############################
# REST API
############################

api = Namespace('webcam', description='Dome Webcam related operations')


@api.route("/position")
class Pointing(Resource):
    """Position of the webcam."""

    def get(self):
        """Retrieve the alt az coordinates of the webcam."""
        res = {
            "response": devices.ipcam.altaz,
            "error": devices.ipcam.error,
        }
        return res

    def put(self):
        """Set new alt az coordinates of the webcam."""
        target = api.payload
        devices.ipcam.altaz = target
        res = {
            "response": devices.ipcam.altaz,
            "error": devices.ipcam.error,
        }
        return res


@api.route("/snapshot")
class Snapshot(Resource):
    """Image from the webcam."""

    def get(self):
        """Retrieve a raw base/64 image from the webcam."""
        res = {
            "response": devices.ipcam.image.decode("ISO-8859-1"),
            "error": devices.ipcam.error,
        }
        return res


############################
# WEB VIEW
############################

web = Namespace('webcam', description='Web webcam interface')


@web.route("/")
class Init(Resource):

    def get(self):
        data = {}
        return make_response(render_template("webcam.html", data=data))


@web.route('/stream')
class Stream(Resource):
    def get(self):
        def inner():
            while True:
                img = devices.ipcam.image
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + img + b'\r\n')
                time.sleep(0.5)

        return Response(inner(), mimetype="multipart/x-mixed-replace; boundary=frame")
