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

"""Web client"""

# System modules

# Third-party modules
from flask import request
from flask_socketio import SocketIO
from astropy.time import Time

# Custom modules
from web.server import routes
from web.server import 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 = [
        "/api/dome/status",
        "/api/telescope/status",
        "/api/camera/status",
        "/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('send_fits')
    def handle_send_fits():
        stream.send_fits(socketio)

        
    @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="/api/dome/status")
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/api/telescope/status")
    socketio.start_background_task(stream.send_status, app=app, socketio=socketio,
                                   url="/api/camera/status")
    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
