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

from flask import render_template, make_response, request
from flask_restx import Namespace, Resource

from .devices_access_object import DevicesObject as DAO

dao = DAO()

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

api = Namespace('devices', description='Devices')

@api.route("/")
class DeviceList(Resource):
    """SHARK devices"""

    def get(self):
        resource = dao.readall()
        return resource

    def post(self):
        data = api.payload["data"]
        #dao.stop(data)
        return dao.home(data), 201

    def put(self):
        motion = api.payload["motion"]
        #action = api.payload["action"]
        data = api.payload["data"]
        dao.stop(data)

        print("posting this:")
        print(data)
        
        if motion == "named":
            return dao.move(data), 201
        elif motion == "relative":
            return dao.relative(data), 201
        elif motion == "absolute":
            return dao.absolute(data), 201

    def delete(self):
        data = api.payload["data"]
        return dao.abort(), 201


@api.route("/<string:device>")
class Device(Resource):
    def get(self, device):
        resource = dao.read(device)
        return resource



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

web = Namespace('devices', description='Web visualization of SHARK devices')

from .data_access_object import SchemaObject as Sch

sch = Sch()

def merge(device=None):

    status = dao.readall()
    options = sch.read("InstrumentSetup")
    
    opt_devs =  { o["name"]: o for o in options if o["name"] in status}

    for dev,val in opt_devs.items():
        opt_devs[dev]["status"] = status[dev]

    return opt_devs


@web.route("/")
class DeviceListWeb(Resource):
    """Show SHARK devices in a web page """
    def get(self):
        """Show all SHARK devices"""
        data = merge()
        return make_response(render_template("devices.html", devices=data))




############################
# Stream
############################

from flask import Response, redirect, url_for, request
import json
import time
from .scheduler import this_scheduler

from astropy.time import Time
now = Time.now()

@this_scheduler.task('interval', seconds=0.5)
def update_json_status():                        
      dao.readall()
      
@web.route('/stream')
class Stream(Resource):
    def get(self):
        def inner():

            previous_res = {}

            while True:

                try:
                    time.sleep(0.2)
                    resource = dao.json_state #dao.readall()
                    if previous_res != resource:
                        yield 'data: {}\n\n'.format(json.dumps(resource))
                    previous_res = resource

                except GeneratorExit:
                    print("Stop streaming devices status")
                    return



        response = inner()
        print(Time.now() - now )
        print("Streaming devices status...")
        return Response(response, mimetype="text/event-stream")
