#!/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')

    base_url = {"ext_base_url": "http://fork.orsa.unige.net:5533", # what browser needs
                "int_base_url": "http://10.185.119.108:5533"} # what server needs
#               "int_base_url": "http://130.251.19.108:5533"} # from outside

    @app.context_processor
    def inject_variables():
        return base_url


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

    
    connected_clients = {}

    ws_names = [
        "all-dome",
        "all-telescope",
        "all-camera",
        "api-sequencer",
        "api-webcam",
        "new-lines",
    ]

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

        print("Sending initial")
        # First connection
        stream.status.initial(socketio, ws_names)
        print("Sent")

        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, socketio=socketio,
                                   name="all-dome", url=base_url["int_base_url"]+"/all/dome")
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                   name="all-telescope", url=base_url["int_base_url"]+"/all/telescope")
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                   name="all-camera", url=base_url["int_base_url"]+"/all/camera?wait=0.2")
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                   name="api-sequencer", url=base_url["int_base_url"]+"/api/sequencer/run")
    socketio.start_background_task(stream.send_webcam, socketio=socketio,
                                    name="api-webcam", url=base_url["int_base_url"]+"/api/webcam/snapshot")
    
    socketio.start_background_task(stream.send_status, socketio=socketio,
                                    name="api-environment", url=base_url["int_base_url"]+"/api/environment/status", sleep=40)

    socketio.start_background_task(stream.send_log, socketio=socketio,
                                   name="new-lines")

    return socketio
