#
#   Copyright © 2021,2022 IsardVDI S.L.
#   Copyright © 2022 Evilham <contact@evilham.com>
#
#   This file is part of DD
#
#   DD is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   DD is distributed in the hope that it will be useful, but WITHOUT ANY
#   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
#   FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
#   details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with DD. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: AGPL-3.0-or-later

from eventlet import monkey_patch

monkey_patch()

import json

from admin.auth.tokens import get_token_payload
from admin.lib.api_exceptions import Error
from flask import request
from flask_login import current_user, login_required
from flask_socketio import (
    SocketIO,
    close_room,
    disconnect,
    emit,
    join_room,
    leave_room,
    rooms,
    send,
)

from admin import get_app
# Set up the app
app = get_app()
app.setup()

app.socketio = SocketIO(app)


@app.socketio.on("connect", namespace="/sio")
@login_required
def socketio_connect() -> None:
    if current_user.id:
        join_room("admin")
        app.socketio.emit(
            "update", json.dumps("Joined admins room"), namespace="/sio", room="admin"
        )
    else:
        None


@app.socketio.on("disconnect", namespace="/sio")
def socketio_disconnect() -> None:
    leave_room("admin")


@app.socketio.on("connect", namespace="/sio/events")
def socketio_connect() -> None:
    jwt = get_token_payload(request.args.get("jwt"))

    join_room("events")
    app.socketio.emit(
        "update",
        json.dumps("Joined events room"),
        namespace="/sio/events",
        room="events",
    )


@app.socketio.on("disconnect", namespace="/sio/events")
def socketio_events_disconnect() -> None:
    leave_room("events")


if __name__ == "__main__":
    app.socketio.run(
        app,
        host="0.0.0.0",
        port=9000,
        debug=False,
    )
    # ssl_context="adhoc",
    # async_mode="threading",
    # )  # , logger=logger, engineio_logger=engineio_logger)
    # , cors_allowed_origins="*"
