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

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

# Third-party modules
from flask import request

from .baseresource import ResourceDev


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

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

    def put(self):
        """Set new alt az coordinates of the webcam."""
        target = request.json
        self.dev.altaz = target
        res = {
            "response": self.dev.altaz,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


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

    def get(self):
        """Retrieve a raw base/64 image from the webcam."""

        img =  self.dev.image
        if not img:
            code = 401
        elif self.dev.error:
            code = 501
        else:
            code = 200

        res = {
            "response": img.decode("ISO-8859-1") if img else img,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }

        return res, code
