import click
import logging
from .session import Session
from .deployment import Deployment
from .supervisor import Supervisor
from .settings import LOGGING_DEFAULTS
logger = logging.getLogger(__name__)


@click.command()
@click.option('--profile', default=None, help='Use this AWS profile to connect to aws.')
@click.option('--assume-role', default=None, help='Assume a role in aws with STS and to execute the deployment')
@click.option('--region', default='us-east-1', help='AWS Region you want to work in.')
@click.option('--bucket', help='S3 bucket you''re authorized to write to.')
@click.option('--key', help='Location in the bucket you want to upload too.')
@click.option('--package', help='Archive you want to deploy.', type=click.Path())
@click.option('--application', help='Name of your code deploy application.')
@click.option('--deployment-group', help='Name of your code deploy deployment group.')
@click.option('--polling', help="Watch the deployment to check for success, or failure", is_flag=True)
@click.option('--polling-interval', default=15, help='Value is set in seconds. If set, the application will poll the deployment group at that interval to see if the deployment is complete. If period is set and not interval, it will default to 60 seconds.')
@click.option('--polling-period', default=600, help='Used with polling-interval, will wait the specified lenght of time in seconds for the deployment to complete. If Interval is set and not period, it will default to 300 seconds.')
@click.option('--deployment-config', default='CodeDeployDefault.OneAtATime', help='Override Deployment Group config.')
def main(profile, assume_role, region, bucket, key, package, application, deployment_group, polling, polling_interval, polling_period, deployment_config):

	startingsession = Session()

	mysession = startingsession.create(profile, assume_role, region)

	myDeployment = Deployment(mysession, bucket, key)
	myDeployment.upload(package)
	myDeployment.deploy(application, deployment_group, deployment_config)

	if polling:
		logging.info('Starting to poll the deployment.')
		mySupervisor = Supervisor(mysession)
		mySupervisor.watch(myDeployment.deploymentId, polling_interval, polling_period)
