from __future__ import print_function

from datetime import datetime

from pybuilder.core import use_plugin, init, task
from pybuilder.errors import BuildFailedException


try:
    import sh  # conditional import, make pyb work w/o it being installed
except ImportError:
    sh = None

use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")
use_plugin("filter_resources")

org_name = "is24"
name = "sample-app"
version = "0.1"
default_task = ['analyze', 'publish']

summary = 'Simple Hello World Webapp!'
description = """tbd."""
url = 'https://github.com/ImmobilienScout24/python-docker-hello-world-webapp'
license = 'Apache License 2.0'

build_version = name + " " + version + " (" + datetime.now().strftime('%d %h %Y %H:%M:%S') + ")"

@init
def set_properties(project):
    project.set_property("verbose", True)

    project.depends_on("bottle")
    project.build_depends_on("webtest")
    project.build_depends_on("docker-py")
    project.build_depends_on("sh")

    project.set_property("name", name)
    project.set_property("version", version)
    project.set_property("build_version", build_version)
    project.set_property("filter_resources_glob", ['**/hello_world/HelloWorldHttpServer.py'])
    project.set_property("dir_dist", "$dir_target/dist/$name-$version")

    project.set_property("flake8_include_test_sources", True)
    project.set_property('coverage_break_build', False)

    project.set_property("install_dependencies_upgrade", True)

    project.set_property('copy_resources_target', '$dir_dist')
    project.set_property('dir_dist_scripts', 'scripts')

    project.set_property('distutils_classifiers', [
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Programming Language :: Python',
        'Topic :: System :: Networking'
    ])


@task
def build_docker(logger):
    if not sh:
        logger.error("The 'sh' module was not found!")
        logger.error("Run 'pyb install_dependencies' to enable this task.")
        raise BuildFailedException('Unable to run task!')
    else:
        for line in sh.docker(['build',
                               '-t',
                               '{0}/{1}:{2}'.format(org_name, name, version),
                               '.',
                               ]):

            print(line.strip())

@@ -1969,39 +1969,77 @@
 )%0A%0A%0A
-@task%0Adef build_docker(logger):
+def check_sh(logger):%0A    %22%22%22 Check if 'sh' module is installed'. %22%22%22
 %0A   
@@ -2243,273 +2243,605 @@
 !')%0A
-    else:%0A        for line in sh.docker(%5B'build',%0A                               '-t',%0A                               '%7B0%7D/%7B1%7D:%7B2%7D'.format(org_name, name, version),%0A                               '.',%0A                               %5D):%0A%0A            print(line.strip()
+%0A%0Adef docker_execute(command_list):%0A    %22%22%22 Run and tail a docker command. %22%22%22%0A    running_command = sh.docker(command_list)%0A    for line in running_command:%0A        print(line.strip())%0A%0A%0A@task%0Adef docker_build(logger):%0A    check_sh(logger)%0A    logger.info(%22Will now attempt to build the docker image.%22)%0A    docker_execute(%5B'build', '-t',%0A                    '%7B0%7D/%7B1%7D:%7B2%7D'.format(org_name, name, version), '.'%5D)%0A%0A%0A@task%0Adef docker_rmi(logger):%0A    check_sh(logger)%0A    logger.info(%22Will now attempt remove the docker image.%22)%0A    docker_execute(%5B'rmi', '%7B0%7D/%7B1%7D:%7B2%7D'.format(org_name, name, version)%5D
 )%0A

refactor and add docker_rmi