#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (c) 2011-2019, Camptocamp SA
# All rights reserved.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:

# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.


from argparse import ArgumentParser
from json import dumps
import re
from urllib.parse import parse_qsl


def _sub(pattern, repl, string, count=0, flags=0, required=True):
    new_string = re.sub(pattern, repl, string, count=count, flags=flags)
    if required and new_string == string:
        print("Unable to find the pattern:")
        print(pattern)
        print("in")
        print(string)
        exit(1)
    return new_string


def _subs(subs, string):
    for pattern, repl in subs:
        if repl is False:
            if re.search(pattern, string) is not None:
                return string
        else:
            new_string = re.sub(pattern, repl, string)
            if new_string != string:
                return new_string
    print("Unable to find the patterns:")
    print(("\n".join([p for p, r in subs])))
    print("in")
    print(string)
    exit(1)


class _RouteDest:

    def __init__(self, constant, route):
        self.constant = constant
        self.route = route

    def __call__(self, matches):
        query_string = matches.group(1)
        query = ''
        if len(query_string) > 0:
            query = ", _query={0!s}".format(dumps(dict(parse_qsl(query_string))))
        return r"module.constant('{0!s}', '${{request.route_url('{1!s}'{2!s}) | n}}');".format(
            self.constant, self.route, query
        )


def main():
    """
    Import the ngeo apps files
    """

    parser = ArgumentParser(description='Import ngeo apps files')

    parser.add_argument('--html', action="store_true", help="Import the html template")
    parser.add_argument('--js', action="store_true", help="Import the javascript controller")
    parser.add_argument('interface', metavar='INTERFACE', help="The interface we import")
    parser.add_argument('src', metavar='SRC', help="The ngeo source file")
    parser.add_argument('dst', metavar='DST', help="The destination file")

    args = parser.parse_args()

    with open(args.src) as src:
        data = src.read()
        data = re.sub(r"{{", r"\\{\\{", data)
        data = re.sub(r"}}", r"\\}\\}", data)

        if args.html:
            data = _sub(
                re.escape('<script src="../../../dist/vendor.js') + r'.*',
                r'<script src="{entry_point}static-ngeo/vendor.js?{cache_version}"></script>'.format(
                    entry_point='${htmlWebpackPlugin.options.vars.entry_point}',
                    cache_version='${htmlWebpackPlugin.options.vars.cache_version}'
                ),
                data,
                required=False,
            )
            data = _sub(
                re.escape('<meta name="dynamicUrl" content="https://geomapfish-demo-') +
                '.*' + re.escape('.camptocamp.com/dynamic.json">'),
                '<meta name="dynamicUrl" content="{entry_point}dynamic.json">'.format(
                    entry_point='${htmlWebpackPlugin.options.vars.entry_point}',
                ),
                data,
            )
            data = _sub(
                re.escape('</head>'),
                '  <link href="{entry_point}static/{version}/css/{interface}.css" rel="stylesheet">\n  </head>'
                .format(
                    entry_point='${htmlWebpackPlugin.options.vars.entry_point}',
                    version='${htmlWebpackPlugin.options.vars.version}',
                    interface=args.interface
                ),
                data,
            )
        else:
            data = re.sub("app", "{{package}}", data)

        with open(args.dst, "wt") as dst:
            dst.write(data)


if __name__ == "__main__":
    main()
