import os
import json
import urllib

from notebook.base.handlers import APIHandler
from notebook.utils import url_path_join

import tornado
from tornado.web import StaticFileHandler
from tornado.httpclient import AsyncHTTPClient, HTTPRequest

class RouteHandler(APIHandler):
    # The following decorator should be present on all verb methods (head, get, post,
    # patch, put, delete, options) to ensure only authorized user can request the
    # Jupyter server
    @tornado.web.authenticated
    async def get(self):
        profile_name = urllib.parse.quote(os.environ.get('OPENSARLAB_PROFILE_NAME', ''))
        lab_short_name = os.environ.get('OPENSARLAB_LAB_SHORT_NAME', '')
        portal_domain = os.environ.get('OPENSARLAB_PORTAL_DOMAIN', '')

        notification_url = f"{portal_domain}/user/notifications/{lab_short_name}?profile={profile_name}"
        req = HTTPRequest(notification_url)
        try:
            response = await AsyncHTTPClient().fetch(req)
            body = response.body.decode('utf8', 'replace')
            if body == 'null':
                body = '[]'
            self.finish(json.dumps({"data": body}))

        except Exception as e:
            self.log.error(f"Error: {e}")
            self.finish(json.dumps({"data": '[]'}))

def setup_handlers(web_app, url_path):
    host_pattern = ".*$"
    base_url = web_app.settings["base_url"]

    # Prepend the base_url so that it works in a JupyterHub setting
    route_pattern = url_path_join(base_url, url_path, "notifications")
    handlers = [(route_pattern, RouteHandler)]
    web_app.add_handlers(host_pattern, handlers)

    # Prepend the base_url so that it works in a JupyterHub setting
    doc_url = url_path_join(base_url, url_path, "public")
    doc_dir = os.getenv(
        "JLAB_SERVER_EXAMPLE_STATIC_DIR",
        os.path.join(os.path.dirname(__file__), "public"),
    )
    handlers = [("{}/(.*)".format(doc_url), StaticFileHandler, {"path": doc_dir})]
    web_app.add_handlers(".*$", handlers)
