#!/usr/bin/python

import os
from pathlib import Path
import subprocess
import re
import shutil
import yaml
from dataclasses import dataclass

CURRENT_DIR = Path(os.path.dirname(__file__))
SRC = CURRENT_DIR.joinpath('../src/gnuboat')
SRC_GEN = CURRENT_DIR.joinpath('../src')
APIS_DIR = CURRENT_DIR.joinpath('../apis')
version_file = open(CURRENT_DIR.joinpath('../VERSION').resolve(), 'r')
VERSION = version_file.read().strip()
version_file.close()

try:
    from dataclasses import dataclass
    

    @dataclass
    class Package:
        """
            package: name of the package (= yaml basename)
            generator: Generator to use
            target: output directrory name, if none, it's set to package
        """
        package: str
        generator: str
        template_folder: Path
        target: str
except:
    # Workaround for @dataclass, until python 3.7 is available in
    # main distros
    class Package:
        """
            package: name of the package (= yaml basename)
            generator: Generator to use
            target: output directrory name, if none, it's set to package
        """
        def __init__(self, package, generator, template_folder, target):
            self.package = package
            self.generator = generator
            self.template_folder = template_folder
            self.target = target


PACKAGES=[
    Package('mapservice', 'python-flask', CURRENT_DIR.joinpath('codegen/templates'), None),
    Package('deviceservice', 'python-flask', CURRENT_DIR.joinpath('codegen/templates'), None),
    Package('mapservice', 'python', None, 'gnuboat/mapservice_client'),
    Package('mapservice', 'typescript-angular', None, 'mapservice-webclient/src-gen/gnuboat-mapservice'),
]

def generate_stub(package, generator, template_folder, target_dir):
    target_tmp = SRC_GEN.joinpath('{}_tmp'.format(package))
    service_specification_file = APIS_DIR.joinpath('{}.yaml'.format(package)).resolve()
    server_port = 8080
    
    target = target_dir.stem
    package_name_gen = 'gnuboat.{}'.format(target)
    target_tmp = SRC_GEN.joinpath('{}_tmp'.format(package))
    target_dir = SRC_GEN.joinpath(target_dir)
    service_specification_file = APIS_DIR.joinpath('{}.yaml'.format(package)).resolve()
    server_port = 8080
    
    openapi_specification = yaml.safe_load(open(service_specification_file))
    if 'servers' in openapi_specification:
        for entry in openapi_specification['servers']:
            if 'description' in entry and 'development' in entry['description'].lower():
                result = re.search(r':([0-9]+)', entry['url'])
                if result is not None:
                    server_port = result.group(1)

    print('Preparing package {} version {} using port {}'.format(package, VERSION, server_port))
    print('  Cleaning directory')
    if target_dir.is_dir():
        shutil.rmtree(target_dir.resolve())
    if target_tmp.is_dir():
        shutil.rmtree(target_tmp.resolve())
    target_tmp.mkdir()

    print('  Generating backend API code in {}'.format(str(target_dir.resolve())))
    arguments = [
        CURRENT_DIR.joinpath('codegen/openapi-generator-cli').resolve(),
        'generate', '-i', service_specification_file,
        '-g', generator,
        ('--additional-properties=packageVersion={},packageName={},'
        'serverPort={}').format(VERSION, package_name_gen, server_port),
        '-o', target_tmp.resolve()
    ]
    if template_folder is not None:
        arguments.append('-t')
        arguments.append(template_folder.resolve())
    try:
        subprocess.run(arguments,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
    except subprocess.CalledProcessError as e:
        print('    openapi-generator-cli failed:')
        print('    STDOUT: {}'.format(e.stdout.decode('utf-8')))
        print('    STDERR: {}'.format(e.stderr.decode('utf-8')))
        return

    if 'python' in generator:
        shutil.move(target_tmp.joinpath('gnuboat/{}'.format(target)).resolve(), target_dir.resolve())
        shutil.rmtree(target_tmp.resolve())
        # running yapf
        print('  Formatting the generated code accoring to style file')
        subprocess.run(['yapf', '--style', CURRENT_DIR.joinpath('../python-style.yapf'), '-r', '-i',
            target_dir.resolve()])
        if 'python-flask' == generator:
            # copy conftest in place
            shutil.copy(target_dir.joinpath(
                '../{}_impl/tests/conftest.py'.format(package)).resolve(),
                target_dir.joinpath('test').resolve()
            )
    else:
        shutil.move(target_tmp, target_dir.resolve())


print('Generating the {} services:'.format(len(PACKAGES)))
for package in PACKAGES:
    print('  {}'.format(package.package))
for package in PACKAGES:
    package_name_gen = 'gnuboat.{}'.format(package)
    if package.target is None:
        package.target = Path('gnuboat').joinpath(package.package)
    else:
        package.target = Path(package.target)
    generate_stub(package.package, package.generator, package.template_folder, package.target)
   

print('Preparing device webclient')
target = SRC.joinpath('deviceservice_impl/static/common')
if target.is_dir():
    shutil.rmtree(target)
target.mkdir()
shutil.copytree(SRC.joinpath('common/resources').resolve(), target.joinpath('resources').resolve())
shutil.copytree(SRC.joinpath('common/lib').resolve(), target.joinpath('lib').resolve())
shutil.copytree(SRC.joinpath('common/css').resolve(), target.joinpath('css').resolve())
shutil.copytree(SRC.joinpath('common/js').resolve(), target.joinpath('js').resolve())
shutil.copytree(SRC.joinpath('common/icon').resolve(), target.joinpath('icon').resolve())
