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

import html
import time
import subprocess
from flask import Response
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

dao = DAO("ob")

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

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

seq = Sequencer()

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

# # New, 2022 Method:

# logging.getLogger('werkzeug').disabled = True

list_of_ob = api.model('list', {
    'id': fields.Integer(readonly=True, description='The OB unique identifier'),
    'name': fields.String(required=True, description='The OB name')
})


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

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

    @api.doc('add_ob')
    @api.expect(list_of_ob)
    @api.marshal_with(list_of_ob, code=201)
    def post(self):
        """Add a new OB to the sequence"""
        data = api.payload


@api.route('/<int:id>')
@api.response(404, 'OB not found')
@api.param('id', 'The OB identifier')
class Bob(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"""

    def get(self):
        """Show the sequencer status"""
        return ""

    def post(self):
        """Start the sequencer"""
        name = api.payload
        filename = dao.show(name)["filename"]
        seq.load_file(filename)
        seq.execute()
        return "", 204

    def delete(self):
        """Stop the sequencer"""
        return "", 204


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


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

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


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

# from .data_access_object import ObservationBlockObject as DAO
# dao = DAO("defaults")
# ############################
# # REST API
# ############################
# api = Namespace('templates', description='Default templates parameters')
# @api.route("/")
# class TemplateList(Resource):
#     def get(self):
#         """Show all template files"""
#         return dao.todos
# @api.route("/<string:name>")
# @api.param("name", "The uniqe name of the template")
# class Template(Resource):
#     def get(self, name):
#         """Show a specific OB"""
#         return dao.show(name)
# ############################
# # WEB VIEW
# ############################
# web = Namespace('templates', description='Defaults template parameters')
# @web.route("/")
# class TemplateListWeb(Resource):
#     def get(self):
#         data = dao.todos
#         print(data)
#         return make_response(render_template("sequencer.html", data=data))
# @web.route("/<string:name>")
# class TemplateWeb(Resource):
#     def get(self, name):
#         included = request.args.get("included") or False
#         data = dao.show(name)
#         data["content"] = data["content"]
#         return make_response(render_template("template.html",
#                                              tpl=data,
#                                              included=included))
############################################################


@web.route('/stream')
class Stream(Resource):
    def get(self):
        def inner():
            proc = subprocess.Popen(
                ['tail -f -n30  ./data/log/OARPAF.2022-06-20.log'],
                #['tail -f /var/log/syslog'],
                shell=True,
                stdout=subprocess.PIPE
            )

            for line in iter(proc.stdout.readline, ''):
                line = line.rstrip().decode()
                line = html.escape(line)
                time.sleep(0.1)
                yield 'data: {}\n\n'.format(line)
                # yield line.rstrip().decode() + '<br/>\n'
        print("qui")
        return Response(inner(), mimetype="text/event-stream")
