# Copyright (c) 2019 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import time

import czid
import czid.czrn as czrn


def convert_arn(arn):
    try:
        converted_czrn = czrn.create_from_arn(arn)
        print(f"ARN            : {arn}\nCZRN           : {converted_czrn}")
        extract_czrn_parts(converted_czrn)
    except ValueError:
        print(f" ARN: {arn} is invalid (czid v{czid.__version__})")


def extract_czrn_parts(czrn_string):
    try:
        service_type, region, account_id, resource_type, cloud_local_id = czrn.extract_all_components(czrn_string)
        print(f"CZID Version   : {czid.__version__}")
        print(f"Service Type   : {service_type}")
        print(f"Region         : {region}")
        print(f"Account ID     : {account_id}")
        print(f"Resource Type  : {resource_type}")
        print(f"Cloud Local ID : {cloud_local_id}")
    except Exception as error:
        print(f"Error: {error}")


def czrn_perf_test(czrn_string):
    print(f"Performance testing various CZID operations {czrn_string}")
    operations = 10000
    results = None

    print(f" - Testing against {operations} operations\n")
    start_time_in_ms = time.time_ns() // 1000000
    for _x in range(operations):
        results = czrn.extract_all_components(czrn_string)
    stop_time_in_ms = time.time_ns() // 1000000
    print(f"Extract all Components via CZID  : {stop_time_in_ms - start_time_in_ms} ms")
    print(f" - Results: {results}")

    start_time_in_ms = time.time_ns() // 1000000
    for _x in range(operations):
        results = czrn_string.split(":")
    stop_time_in_ms = time.time_ns() // 1000000
    print(f"Extract all Components via split : {stop_time_in_ms - start_time_in_ms} ms")
    print(f" - Results: {results[2:]}")

    start_time_in_ms = time.time_ns() // 1000000
    for _x in range(operations):
        results = czrn.extract_account_id(czrn_string)
    stop_time_in_ms = time.time_ns() // 1000000
    print(f"Extract Account ID via CZID      : {stop_time_in_ms - start_time_in_ms} ms")
    print(f" - Results: {results}")

    start_time_in_ms = time.time_ns() // 1000000
    for _x in range(operations):
        results = czrn_string.split(":")[4]
    stop_time_in_ms = time.time_ns() // 1000000
    print(f"Extract Account ID via split     : {stop_time_in_ms - start_time_in_ms} ms")
    print(f" - Results: {results}")
