# 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; witout 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 flask
import pkg_resources
import yaml
import hashlib


def prepare_blueprint(app):
    """Prepare a blueprint containing all the redirects"""
    raw = pkg_resources.resource_string("uitwww", "data/redirects.yml")
    config = yaml.safe_load(raw.decode("utf-8"))

    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
