"""
Tasks for deploying Rookeries.

:copyright: Copyright 2013-2015, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import pathlib

import invoke as inv
import arrow

import rookeries
from . import clean, utils


@inv.ctask(clean.python, clean.assets)
def package(ctx, add_date_suffix=False, package_suffix=''):
    """
    Prepares the project for packaging.

    :param add_date_suffix: Flag for adding for removing a date suffix to the package.
    :param package_suffix: An aditional suffix to add to the file name.
    """
    deploy_staging_path = generate_package_name(add_date_suffix, package_suffix)
    deployable_package = "{}.tar.bz2".format(deploy_staging_path)

    utils.delete_in_path_list([deploy_staging_path, deployable_package])

    packaging_dir = pathlib.Path(deploy_staging_path)
    if not packaging_dir.exists():
        packaging_dir.mkdir()

    ctx.run('ln -s ../rookeries {}/rookeries'.format(packaging_dir))
    ctx.run('ln -s ../client {}/client'.format(packaging_dir))
    ctx.run('ln -s ../requirements.txt {}/requirements.txt'.format(packaging_dir))
    ctx.run('ln -s ../package.json {}/package.json'.format(packaging_dir))

    ctx.run('tar zcvhf {} {}'.format(deployable_package, packaging_dir), echo=True)
    ctx['deployable'] = pathlib.Path(deployable_package)


def generate_package_name(add_date_suffix=False, pkg_suffix=''):
    """
    Generate the name of the app package for this deployment.

    :param add_date_suffix: Flag for adding for removing a date suffix to the package.
    :param pkg_suffix: An aditional suffix to add to the file name.
    :return: The name of the app package
    """

    package_name = [
        rookeries.__name__,
        rookeries.__version__
    ]

    if pkg_suffix:
        package_name.append(pkg_suffix)

    if add_date_suffix:
        date_suffix = arrow.now().format('YYYYMMDD-HHmm')
        package_name.append(date_suffix)

    return '-'.join(package_name)
