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

'''REST API for Telescope related operations'''

# System modules
from datetime import datetime

# Third-party modules
from flask import request

# Custom modules
from config import constants
from utils.coordinates import to_hms, to_hms_dms, to_radec
from .baseresource import ResourceDev


# @api.route("/cover")
class Cover(ResourceDev):
    '''Petals covering the primary mirror.'''

    def get(self):
        '''Retrieve the petals position.'''
        res = {
            "response": self.dev.cover,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/cover/movement")
class CoverMovement(ResourceDev):
    '''Manage the primary mirror cover petals.'''

    # def get(self):
    #     '''Check if petals are moving.'''
    #     return

    def post(self):
        '''Set a new position for cover petals
        (open or closed).'''
        target = request.json # api.payload
        self.dev.open = target
        res = {
            "response": self.dev.open,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    # def delete(self):
    #     '''Stop the movement.'''
    #     return


# @api.route("/error")
class Error(ResourceDev):
    '''Manage the cabinet errors.'''

    def get(self):
        '''Check if there are errors.'''
        res = {
            "response": self.dev.state,  # state is global
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    def delete(self):
        '''Try to clean the errors.'''
        error_number = request.json
        res = {
            "response": self.dev.clear(error_number),
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

# @api.route("/error/details")
class ErrorDetails(ResourceDev):
    '''Get the global status to have more info.'''

    def get(self):
        '''Check if there are errors.'''
        res = {
            "response": self.dev.status,  # state is global
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/clock")
class Clock(ResourceDev):
    '''Telescope time from GPS.'''

    def get(self):
        '''Get the telescope time from GPS.'''
        res = {
            "response": self.dev.clock,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates")
class Coordinates(ResourceDev):
    '''Telescope coordinates.'''

    def get(self):
        '''Get the telescope coordinates.'''
        coor = self.dev.coordinates
        lst = coor["lst"]
        ra = coor["radec"][0]
        coor["ha"] = to_hms(lst-ra)
        coor["radec"] = to_hms_dms(coor["radec"])
        coor["lst"] = to_hms(coor["lst"])
        utc = coor["utc"]
        coor["utc"] = datetime.fromtimestamp(utc).isoformat()

        res = {
            "response": coor,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement")
class CoordinatesMovement(ResourceDev):
    '''Manage the pointing of the telescope.'''

    def get(self):
        '''Check the status of the telescope movement.'''
        res = {
            "response": self.dev.is_moving,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    def delete(self):
        '''Stop the telescope movement.'''
        res = {
            "response": self.dev.abort(),
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement/radec")
class CoordinatesMovementRadec(ResourceDev):
    '''Point the telescope in Ra, Dec.'''

    def post(self):
        '''Set new Ra and Dec coordinates.'''
        target = request.json

        radec = to_radec(target)

        print(radec)

        self.dev.radec = radec
        res = {
            "response": self.dev.radec,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement/altaz")
class CoordinatesMovementAltaz(ResourceDev):
    '''Point the telescope in Alt, Az.'''

    def post(self):
        '''Set new Alt and Az coordinates.'''
        target = request.json
        self.dev.altaz = target
        res = {
            "response": self.dev.altaz,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement/atpark")
class CoordinatesMovementAtpark(ResourceDev):
    '''Park the telescope.'''

    def get(self):
        '''Send the telescope to park position.'''
        parked = self.dev.park
        res = {
            "raw": parked,
            "response": constants.yes_no[parked],
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement/park")
class CoordinatesMovementPark(ResourceDev):
    '''Park the telescope.'''

    def post(self):
        '''Send the telescope to park position.'''
        self.dev.park = True
        res = {
            "response": self.dev.park,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/movement/unpark")
class CoordinatesMovementUnpark(ResourceDev):
    '''Unpark the telescope.'''

    def post(self):
        '''Remove the telescope from park position.'''
        self.dev.park = False
        res = {
            "response": self.dev.park,
            "error": self.dev.error,
            "timestamp": self.timestamp,
               }
        return res


# @api.route("/coordinates/offset")
class CoordinatesOffset(ResourceDev):
    '''Manage the coordinates offset.'''

    def get(self):
        '''Retrieve the telescope offset in Zdist, Az.'''
        res = {
            "response": self.dev.offset,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    def put(self):
        '''Apply to the telescope new offsets in degrees.'''
        offset = request.json
        self.dev.offset = offset
        res = {
            "response": self.dev.offset,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/coordinates/tracking")
class CoordinatesTracking(ResourceDev):
    '''Enable or disable the telescope tracking.'''

    def get(self):
        '''Check if the telescope is tracking or not.'''
        res = {
            "raw": self.dev.tracking,
            "response": constants.yes_no[self.dev.tracking],
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    def put(self):
        '''Set the telescope in tracking mode or not'''
        tracking = request.json
        self.dev.tracking = tracking
        res = {
            "response": self.dev.tracking,
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


# @api.route("/connection")
class Connection(ResourceDev):
    '''Manage the connection to ASCOM.'''

    def get(self):
        '''Check if the telescope is connected to ASCOM.'''

        res = {
            "raw": self.dev.connection,
            "response": constants.yes_no[self.dev.connection],
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res

    def put(self):
        '''Connect or disconnect the telescope to ASCOM.'''

        connection = request.json
        self.dev.connection = connection
        res = {
            "raw": self.dev.connection,
            "response": constants.yes_no[self.dev.connection],
            "error": self.dev.error,
            "timestamp": self.timestamp,
        }
        return res


#         clock = Clock(dev=self.dev).get()
#         if clock["response"] and type(clock["response"]) != str:

#             # 2) astelOS has data from the GPS

#             connection = Connection(dev=self.dev).get()
#             if connection["response"]:

#                 # 3) Telescope manually connected to ASCOM

#             else:

#                 # 3) No telescope ASCOM connection

#         else:
#             # 2) AstelOS not ready

#         return res
