import cfnresponse
import boto3
codeCommit = boto3.client('codecommit')
s3 = boto3.resource('s3')
ecr = boto3.client('ecr')
def lambda_handler(event, context):
    responseData = {'status': 'NONE'}
    if event['RequestType'] == 'Create':
        repoName = event['ResourceProperties'].get('RepoName')
        branch_names = event['ResourceProperties'].get('BranchNames')
        branches = codeCommit.list_branches(repositoryName=repoName)['branches']
        responseData['default_branch'] = branch_names[0] 
        if len(branches) == 0:
            putFiles = {'filePath': 'buildspec.yml', 'fileContent': "version: 0.2\nphases:\n  build:\n    commands:\n      - echo 'dummy'\n".encode()}
            resp = codeCommit.create_commit(repositoryName=repoName, branchName='master', commitMessage=' - repo init', putFiles=[putFiles])
            for i in branch_names:
                codeCommit.create_branch(repositoryName=repoName, branchName=i, commitId=resp['commitId'])
            responseData['status'] = 'CREATED'
    elif event['RequestType'] == 'Delete':
        s3.Bucket( event['ResourceProperties'].get('BucketName') ).object_versions.all().delete()
        try:
            for i in event['ResourceProperties'].get('ImageRepoNames'):
                imgs = ecr.list_images(registryId='894268508623', repositoryName=i)
                ecr.batch_delete_image(registryId='894268508623', repositoryName=i, imageIds=imgs['imageIds'])
        except Exception as e:
            pass
        responseData['status'] = 'DELETED'
    cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
