from subprocess import call
import os
from pybuilder.core import use_plugin, init, task, depends, description
from pybuilder.errors import BuildFailedException
import zipfile

use_plugin('python.core')
use_plugin('python.install_dependencies')


@init
def initialize(project):
    project.build_depends_on('boto3', '==1.4.4')

    project.set_property('dir_dist', '$dir_target/dist/python-serverless-example')


@task
@depends('package')
@description('Package the project for deployment')
def package_serverless(logger):
    with zipfile.ZipFile('target/dist/serverless.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk('target/dist/python-serverless-example'):
            for file in files:
                zipf.write(os.path.join(root, file),
                           os.path.relpath(os.path.join(root, file), 'target/dist/python-serverless-example'))


@task
@depends('package_serverless')
@description('Deploy the project to AWS')
def deploy(logger):
    ret = call('sls deploy', shell=True)
    if ret != 0:
        logger.error("Error deploying project to AWS")
        raise BuildFailedException


@task
@description('Removes the project from AWS')
def remove(logger):
    ret = call('sls remove', shell=True)
    if ret != 0:
        logger.error('Error removing the deployment from AWS')
        raise BuildFailedException