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

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

# System modules
#import time

# Third-party modules
from flask_restx import Namespace, Resource, fields

# 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."""

        img =  devices.ipcam.image
        if not img:
            code = 401
        elif devices.ipcam.error:
            code = 501
        else:
            code = 200
        
        res = {
            "response": img.decode("ISO-8859-1") if img else img,
            "error": devices.ipcam.error,
        }
        
        return res, code
