# encoding: utf-8
"""
OOS Cloud Trail Python API Example
"""
from ctyun.config import Config
from ctyun.cloudtrail.client import TrailClient
from ctyun.auth.credentials import Credentials
from ctyun.cloudtrail.model.request import *
import ctyun.exceptions as exceptions
import traceback
import time

ACCESS_KEY = 'your_accessKey'
SECRET_KEY = 'your_secretKey'
TRAIL_ENDPOINT = 'your_domain'
SIGNATURE_VERSION = 'v4'  # Algorithm version used for calculating signatures, v2 version:'v2', v4 version:'v4'
BUCKET = 'your_bucket'  # bucket name
REQ_NAME = 'your_trailName'  # trail name
KRY_PREFIX = "your_prefix/"  # prefix of trail log

# Preprocessing, setting up access to Cloud Trail service
if TRAIL_ENDPOINT.lower().find("http") < 0 and TRAIL_ENDPOINT.lower().find("https") < 0:
    TRAIL_ENDPOINT = "https://" + TRAIL_ENDPOINT
try:
    config = Config()
    config.signature_version = SIGNATURE_VERSION
    credentials = Credentials(ACCESS_KEY, SECRET_KEY)
    trail_client = TrailClient(credentials, config, TRAIL_ENDPOINT, False)
except Exception as ex:
    print(traceback.format_exc())
    print(ex)
    exit(-1)


def handle_error(fn):
    """
    Exception handling
    """

    def inner():
        try:
            fn()
        except exceptions.ServiceException as e:
            print(e.get_header().to_string())
            print(e.to_string())

    return inner


# 1	Create Trail
@handle_error
def create_trail_example():
    """
    This operation is used to create a trace and save the trace log to the specified OOS bucket
    """
    request = CreateTrailRequest()
    # Specify the name of the trace
    request.name = REQ_NAME
    # Name of the bucket
    request.s3BucketName = BUCKET
    # Specify the prefix for the name of the trace log
    request.s3KeyPrefix = KRY_PREFIX

    result = trail_client.create_trail(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 2	Delete Trail
@handle_error
def delete_trail_example():
    """
    This operation is used to delete the specified trace
    """
    request = DeleteTrailRequest()
    # Specify the name of the trace
    request.name = REQ_NAME

    result = trail_client.delete_trail(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 3	Describe Trails
@handle_error
def describe_trail_example():
    """
    This operation is used to obtain the setup information of the operation trace
    """
    request = DescribeTrailsRequest()
    # Specify the name of the trace List
    request.name_list = [REQ_NAME]

    result = trail_client.describe_trail(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 4	Get Trail Status
@handle_error
def get_trail_status_example():
    """
    This operation is used to obtain trace status information
    """
    request = GetTrailStatusRequest()
    # Specify the name of the trace
    request.name = REQ_NAME

    result = trail_client.get_trail_status(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 5	Put Event Selectors
@handle_error
def put_event_selectors_example():
    """
    This operation is used to configure the management event filter for the trace
    """
    request = PutEventSelectorsRequest()
    # Specify the name of the trace
    request.trail_name = REQ_NAME
    # Specify the management event filter
    selectors_list = []
    selector = EventSelect()
    # Specify the read/write type of the management event, values: ALL/ReadOnly/WriteOnly
    selector.read_write_type = "All"
    selectors_list.append(selector)
    request.selector_list = selectors_list

    result = trail_client.put_event_selectors(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 6	Get Event Selectors
@handle_error
def get_event_selectors_example():
    """
    This operation is used to view the setup information of the management event filter
    """
    request = GetEventSelectorsRequest()
    # Specify the name of the trace
    request.trail_name = REQ_NAME

    result = trail_client.get_event_selectors(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 7	Update Trail
@handle_error
def update_trail_example():
    """
    This operation is used to update trace setup parameters,
    including the OOS Bucket in which the trace log data is saved, and the trace log prefix
    """
    request = UpdateTrailRequest()
    # Specify the name of the trace
    request.name = REQ_NAME
    # Name of the bucket
    request.s3BucketName = BUCKET
    # Specify the prefix for the name of the trace log
    request.s3KeyPrefix = KRY_PREFIX

    result = trail_client.update_trail(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 8	Start Logging
@handle_error
def start_logging_example():
    """
    This operation is used to enable trace
    """
    request = StartLoggingRequest()
    # Specify the name of the trace
    request.name = REQ_NAME

    result = trail_client.start_logging(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 9	Stop Logging
@handle_error
def stop_logging_example():
    """
    This operation is used to unable trace
    """
    request = StopLoggingRequest()
    # Specify the name of the trace
    request.name = REQ_NAME

    result = trail_client.stop_logging(request)

    print(result.get_header().to_string())
    print(result.to_string())


# 10 Lookup Events
@handle_error
def lookup_events_example():
    """
    This operation is used to view the management events in the account.
    Users can view management events that have occurred in the last 6 months
    """
    request = LookupEventsRequest()
    # Specify the start time for returning management event
    request.start_time = str(int((round(time.time() - 5 * 24 * 60 * 60) * 1000)))
    # Specify the end time for returning management event
    request.end_time = str(int(round(time.time() * 1000)))
    # Specify the query attribute for the management event
    lookup_attribute_list = []
    lookup_attribute = LookupAttribute()
    # Specify the attribute key for querying management event
    lookup_attribute.attribute_key = ""
    # Specify the value corresponding to AttributeKey
    lookup_attribute.attribute_value = ""
    lookup_attribute_list.append(lookup_attribute)
    request.lookup_attribute_list = lookup_attribute_list
    # Set the maximum number of returned responses, value: 1~50
    request.max_results = str(20)

    result = trail_client.lookup_events(request)

    print(result.get_header().to_string())
    print(result.get_event(0).to_string())


if __name__ == '__main__':
    try:
        # 1	Create a trail, and save the trail logs in the specified OOS bucket
        # create_trail_example()

        # 2	Delete the specified trail
        # delete_trail_example()

        # 3	Retrieve settings information of trails
        describe_trail_example()

        # 4	Get the trail status information
        # get_trail_status_example()

        # 5	Configure a management event selector for specified trail
        # put_event_selectors_example()

        # 6	Get the setting information of the management event selector for the specified trail
        # get_event_selectors_example()

        # 7	Update the setting information of the trail
        # update_trail_example()

        # 8	Enable CloudTrail
        # start_logging_example()

        # 9	Disable CloudTrail
        # stop_logging_example()

        # 10 Look up the management event within the OOS account
        # lookup_events_example()

    except Exception as ex:
        print(traceback.format_exc())
        print(ex)
