from check_snapshots_utils import *

def lambda_handler(event, context):
    snap_items = getSnapshotRecords("snap_state")

    pending_creating_snapshots = 0

    if snap_items.__len__() > 0:
        # Check if snapshots are still in creating state
        for item in snap_items:
            logger.info("Snapshot '{}' is still in '{}' state. Checking new status.".format(item["Snapshot_ID"]["S"], item["Snapshot_State"]["S"]))

            # Get Cluster Snapshot state if item is Aurora
            if item['RDS_Engine']['S'] == 'aurora':
                tmpSnapState = checkClusterSnapshotState(item["Snapshot_ID"]["S"])
            
            # Get Instance Snapshot state if item is instance
            else:
                tmpSnapState = checkRdsSnapshotState(item["Snapshot_ID"]["S"])

            # If snapshot was not found
            if tmpSnapState == "not found":

                logger.error("Could not get {} snapshots state from RDS. Possible that it doesn't exist anymore".format(item['Snapshot_ID']['S']))

                # Check if snapshot was deleted by "DeleteSnapshots" function
                # If false, snapshot has been deleted manually
                if item['Deleted']['BOOL'] == False:
                    manageSnapshotRecord(action = 'update', snapshot_id = item["Snapshot_ID"]["S"], rds_name = item["RDS_Name"]["S"], snapshot_state = tmpSnapState, deleted_bool = True, emailed_bool = False) 
                
            elif tmpSnapState != "creating":
                logger.info("Snapshot '{}' is now in '{}' state. Updating DB.".format(item["Snapshot_ID"]["S"], tmpSnapState))
                manageSnapshotRecord(action = 'update', snapshot_id = item["Snapshot_ID"]["S"], rds_name = item["RDS_Name"]["S"],snapshot_state = tmpSnapState)
            else:
                logger.info("Snapshot '{}' is still in '{}' state.".format(item["Snapshot_ID"]["S"], tmpSnapState))
                pending_creating_snapshots += 1

    else:
        logger.info("No snapshots in creating state found.")

    if pending_creating_snapshots > 0:
        log_message = "There are still {} snapshot(s) in creating state.".format(pending_creating_snapshots)
        logger.error(log_message)
        raise RDSBackupToolException(log_message)
    
if __name__ == '__main__':
    lambda_handler(None, None)