# BFH Science Self-Service Portal
# Copyright (C) 2025-2026 IKUS Software
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import cherrypy
import requests
from cherrypy_foundation.url import url_for


class IdentityHandler:
    """
    Handler for identity card.
    """

    @cherrypy.expose()
    @cherrypy.tools.allow(methods=['GET'])
    @cherrypy.tools.auth(on=False)
    def img(self, u=None, **kwargs):
        """
        Proxy image from another web service.
        """
        username = u or cherrypy.serving.request.login
        cfg = cherrypy.tree.apps[''].cfg
        if cfg.user_image_url and '%s' in cfg.user_image_url:
            try:
                url = cfg.user_image_url % (username,)
                response = requests.get(url, stream=True, timeout=5)
                response.raise_for_status()
                content_type = response.headers.get('Content-Type', 'image/jpeg')
                cherrypy.response.headers['Content-Type'] = content_type
                cherrypy.response.headers['Content-Disposition'] = 'inline; filename="downloaded_image"'
                return response.content
            except Exception:
                pass
        # If picture cannot be downloaded redirect to a static file.
        raise cherrypy.HTTPRedirect(url_for('static', 'portrait-placeholder.png'))
