#!/usr/bin/env python3
# -*- 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


def enable(app):

    app.template_folder = "./web/pages"
    app.static_folder = "./web/static"

    app.register_blueprint(routes.web, url_prefix='/web')

    socketio = SocketIO(app,
                        path="/web/socket",
                        async_mode='threading',
                        threaded=True)

    connected_clients = {}

    ws_names = [
        "/all/dome",
        "/all/telescope",
        "/all/camera?wait=0.2",
        "/api/sequencer/run",
        "/api/webcam/snapshot",
        "new_lines",
    ]

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

        # First connection
        stream.status.initial(socketio, ws_names)

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

        print(f"Connected:    {client_id} - IP: {client_ip}. Tabs: {len(connected_clients)}, IPs: {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(f"Disconnected: {client_id} - IP: {client_ip}. Tabs: {len(connected_clients)}, IPs: {uniques}")

    @socketio.on_error()
    def error_handler(e):
        print(f'ERROR: {e}')


    
    # socketio.start_background_task(send_binary, socketio=socketio)

    socketio.start_background_task(stream.send_timestamp, socketio=socketio)

    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/all/dome")
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/all/telescope")
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/all/camera?wait=0.2")
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/api/sequencer/run")
    socketio.start_background_task(stream.send_webcam, app=app, socketio=socketio,
                                   url="/api/webcam/snapshot")
    
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                    url="/api/environment/status", sleep=40)

    socketio.start_background_task(stream.tail_f, socketio=socketio)

    return socketio
