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

# System modules
from flask_restx import Namespace, Resource, fields, Model

# Custom modules
import devices

api = Namespace('environment', description='Environment data from multiple devices')


@api.route("/")
class Meteo(Resource):
    """Asks all the environment data"""

    @api.response(200, 'Success')
    def get(self):
        """Downloads all the environment values available """
        meteo = Meteo().get()
        internal = Internal().get()
        #meteo.update(internal)
        return {"external":meteo, "internal":internal}

@api.route("/meteo")
class Meteo(Resource):
    """Asks all the meteo station data"""

    @api.response(200, 'Success')
    def get(self):
        """Downloads the current meteo station values"""
        return devices.met.data

@api.route("/meteo/clock")
class MeteoClock(Resource):
    """Manages the meteo panel clock"""

    @api.response(200, 'Success')
    def get(self):
        """Retrieve the current date and time of the panel"""
        return devices.met.time

    @api.response(200, 'Success')
    def put(self):
        """Syncronize the panel date and time with the pc calling this."""
        return devices.met.synctime()

@api.route("/internal")
class Internal(Resource):
    """Asks all the meteo station data"""

    @api.response(200, 'Success')
    def get(self):
        """Downloads the current meteo station values"""

        try:
            telescope_temperatures = devices.tel.temperature
        except:
            telescope_temperatures = [None, None, None]

        try:
            camera_ambient = devices.cam.ambient
        except:
            camera_ambient = None
            
        res = {
            "Temperature_dome": camera_ambient,

            "Temperature_M1": telescope_temperatures[0],
            "Temperature_M2": telescope_temperatures[1],
            "Temperature_cabinet": telescope_temperatures[2],
            
            "Temperature_fork": devices.fork.temperature,
            "Humidity_fork": devices.fork.humidity,
            "Time_fork_data": devices.fork.last_update,
            
            "Temperature_rack": devices.rack.temperature,
            "Humidity_rack": devices.rack.humidity,
            "Time_rack_data": devices.rack.last_update,
            
            "Temperature_reception": devices.rec.temperature,
            "Humidity_reception": devices.rec.humidity,
            "Time_reception_data": devices.rec.last_update,
            }
        
        return res 
