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

"""Web client"""

# System modules

# Third-party modules
from flask import request
from flask_socketio import SocketIO

# Custom modules
from web.server import routes, stream
from templates.util import variables as uvars

def enable(app):

    app.template_folder = uvars.pythonDir+"/web/pages"
    app.static_folder =  uvars.pythonDir+"/web/static"
    
    app.register_blueprint(routes.web, url_prefix='/web')

    socketio = SocketIO(app,
                        path="/web/socket",
                        # async_mode='threading',
                        # transports=["websocket"],
                        threaded=True,
                        binary=True,
                        )
    
    connected_clients = {}

    ws_names = [
        "json-status",
        "rtc-status",
        "new-lines",
    ]

    @socketio.on('connect')
    def handle_connect():

        client_id = request.sid
        client_ip = request.remote_addr
        connected_clients[client_id] = client_ip
        uniques = len(set(connected_clients.values()))

        print("sending initial to client {}".format(client_id))
        # First connection
        stream.status.initial(socketio, ws_names, client=client_id)
        #stream.tail_f(socketio,u'new-lines',once=True )
        print("sent")

        print("Connected:    {} - IP: {}. Tabs: {}, IPs: {}".format(client_id, client_ip,
                                                                    len(connected_clients), uniques))


    @socketio.on('disconnect')
    def handle_disconnect():
        client_id = request.sid
        client_ip = request.remote_addr

        if client_id in connected_clients:
            del connected_clients[client_id]

        uniques = len(set(connected_clients.values()))

        print("Disconnected: {} - IP: {}. Tabs: {}, IPs: {}".format(client_id, client_ip,
                                                                    len(connected_clients), uniques))

    @socketio.on_error()
    def error_handler(e):
        print('ERROR: {}'.format(e))
    
    
    socketio.start_background_task(stream.send_timestamp, socketio=socketio,
                                   name=u'timestamp')
    
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                   name=u"json-status", url="/api/devices/")
    
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                   name=u"rtc-status", url="/api/rtc/plots/")
    
    socketio.start_background_task(stream.tail_f, socketio=socketio,
                                   name=u"new-lines")
    
    socketio.start_background_task(stream.send_cred, socketio=socketio,
                                   name=u"data-cred")
    
    socketio.start_background_task(stream.send_dm, socketio=socketio,
                                   name=u"data-dm")

    return socketio
