# Source code of the Ubuntu-it website
# Copyright (C) 2018 Pietro Albini <pietroalbini@ubuntu.com>
#
# This program 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.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import yaml
import flask
import hashlib

from .constants import UITWWW_DIR


def prepare_blueprint(app):
    """Prepare a blueprint containing all the redirects"""
    with open(UITWWW_DIR + "/data/redirects.yml") as fn:
        config = yaml.safe_load(fn.read())

    bp = flask.Blueprint("redirects", __name__)

    for origin, dest in config["external"].items():
        endpoint = "ext_" + hashlib.sha1(origin.encode("utf-8")).hexdigest()[:10]

        @bp.route(origin, endpoint=endpoint)
        def _(_dest=dest):
            return flask.redirect(_dest)

    for origin, dest in config["internal"].items():
        endpoint = "int_" + hashlib.sha1(origin.encode("utf-8")).hexdigest()[:10]

        @bp.route(origin, endpoint=endpoint)
        def _(_dest=dest):
            _dest.setdefault("args", {})
            return flask.redirect(
                flask.url_for(_dest["endpoint"], **_dest["args"])
            )

    return bp
