#!/usr/bin/env python

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

from .data_access_object import ObservationBlockObject as DAO

from sequencer import Sequencer
from util import exception

dao = DAO("/opt/tan/share/shins/saved")

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

api = Namespace('sequencer', description='Sequencer')

import logging
api.logger.disabled = True
log = logging.getLogger('werkzeug')
log.disabled = True

# # Old method
# log = logging.getLogger('SHINS')
# log.disabled = True

# New, 2022 Method:
logging.getLogger('werkzeug').disabled = True

@api.route("/")
class BobList(Resource):
    """Show and modify a list of OBs to be sequencerd"""

    @api.doc('list_ob')
    def get(self):
        """Show all OB in the sequence"""
        return dao.todos

    @api.doc('add_ob')
    def post(self):
        """Add a new OB to the sequence"""
        data = api.payload
        return dao.create(name), 201


@api.route('/<int:id>')
@api.response(404, 'OB not found')
@api.param('id', 'The OB identifier')
class Todo(Resource):
    '''Let delete a specific OB'''

    @api.doc('delete_ob')
    @api.response(204, 'OB deleted')
    def delete(self, id):
        '''Delete an OB given its identifier'''
        dao.delete(id)
        return '', 204


@api.route("/run")
class BobRun(Resource):
    """Manage the sequencer"""

    seq = Sequencer()

    def get(self, seq=seq):
        """Show the sequencer status"""
        name = seq.tpl.name if seq.tpl else None
        res = {
            "response": name,
            "error": seq.error,
        }
        return res


    def put(self, seq=seq):
        """Pause or resume the template execution. Inverting the logic with
        respect to sequencer class:
        PUT /sequencer/run true: resume,
        PUT /sequencer/run false: pause
        PUT /sequencer/run null: retry
        """
        in_execution = api.payload
        seq.resume() if in_execution else seq.pause()
        res = {
            "response": seq.tpl.paused,
            "error": seq.error,
        }
        return res


    def post(self, seq=seq):
        """Start the sequencer"""
        name = api.payload
        try:
            filename = dao.show(name)["filename"]
        except TypeError as e:
            res = {
                "response": None,
                "error": ["Web interface: no filename provided", e],
            }
            return res, 500

        if seq:
            seq.ob_file = filename
            seq.execute()
            res = {
                "response": seq.tpl.paused,
                "error": seq.error,
            }
        else:
            res = {
                "response": "There is no seq",
                "error": "There is no seq",
            }

        return res, 204


    def delete(self, seq=seq):
        """Stop the sequencer"""

        try:
            seq.quit()            

            res = {
                "response": "OB Stopped",
                "error": seq.error,
            }
            
        except exception.TemplateException("TemplateException catched on bob") as te:
            res = {
                "response": "OB Stopped",
                "error": "catched exception here",
            }
            
        return res

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


web = Namespace('sequencer', description='Web Sequencer interface')

@web.route("/")
class BobWeb(Resource):

    def get(self):
        data = sorted(dao.todos)
        return make_response(render_template("sequencer.html", data=data))


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

from flask import Response
import subprocess
import time
import html

@web.route('/stream')
class Stream(Resource):
    def get(self):
        def inner():
            try:
                proc = subprocess.Popen(
                    ['tail -n 100 -F /data/log/log_of_python_test.log'],
                    shell=True,
                    stdout=subprocess.PIPE
                )

                for line in iter(proc.stdout.readline,''):
                    line = line.rstrip().decode()
                    #line = html.escape(line)
                    time.sleep(0.05)
                    yield 'data: {}\n\n'.format(line)
            except GeneratorExit as e:
                print(e)
                print("Closing subprocess")
                proc.terminate()
                proc.wait()
                print("Subprocess close2d")

        print("Streaming template log...")
        return Response(inner(), mimetype="text/event-stream")
