"""
"""

import phantom.rules as phantom
import json
from datetime import datetime, timedelta
def on_start(container):
    phantom.debug('on_start() called')
    
    # call 'format_1' block
    format_1(container=container)

    return

def format_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('format_1() called')
    
    template = """| savedsearch peer_list server=\"{0}{1}\""""

    # parameter list for template variable replacement
    parameters = [
        "artifact:*.cef.destinationHostName",
        "artifact:*.cef.destinationAddress",
    ]

    phantom.format(container=container, template=template, parameters=parameters, name="format_1")

    run_query_1(container=container)

    return

def run_query_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('run_query_1() called')

    # collect data for 'run_query_1' call
    formatted_data_1 = phantom.get_format_data(name='format_1')

    parameters = []
    
    # build parameters list for 'run_query_1' call
    parameters.append({
        'query': formatted_data_1,
        'display': "",
    })

    phantom.act(action="run query", parameters=parameters, assets=['esachuryn02'], callback=format_2, name="run_query_1")

    return

def add_comment_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('add_comment_1() called')

    formatted_data_1 = phantom.get_format_data(name='format_2')

    phantom.comment(container=container, comment=formatted_data_1)
    cf_local_store_peer_list_as_customlist_1(container=container)

    return

def update_event_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('update_event_1() called')
        
    #phantom.debug('Action: {0} {1}'.format(action['name'], ('SUCCEEDED' if success else 'FAILED')))
    
    # collect data for 'update_event_1' call
    container_data = phantom.collect2(container=container, datapath=['artifact:*.cef.event_id', 'artifact:*.id'])
    formatted_data_1 = phantom.get_format_data(name='format_3')

    parameters = []
    
    # build parameters list for 'update_event_1' call
    for container_item in container_data:
        if container_item[0]:
            parameters.append({
                'owner': "",
                'status': "in progress",
                'comment': formatted_data_1,
                'urgency': "critical",
                'event_ids': container_item[0],
                # context (artifact id) is added to associate results with the artifact
                'context': {'artifact_id': container_item[1]},
            })

    phantom.act(action="update event", parameters=parameters, assets=['esachuryn02'], callback=playbook_local_local_Malware_Critical_Peer_Container_ch02_1, name="update_event_1")

    return

def format_2(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('format_2() called')
    
    template = """The infected server Host Name = {0}, IP = {1} has {2} peers that it communicated with."""

    # parameter list for template variable replacement
    parameters = [
        "artifact:*.cef.destinationHostName",
        "artifact:*.cef.destinationAddress",
        "run_query_1:action_result.summary.total_events",
    ]

    phantom.format(container=container, template=template, parameters=parameters, name="format_2")

    add_comment_1(container=container)

    return

def format_3(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('format_3() called')
    
    template = """The notable event is being processed by Phantom, see {0}"""

    # parameter list for template variable replacement
    parameters = [
        "container:url",
    ]

    phantom.format(container=container, template=template, parameters=parameters, name="format_3")

    update_event_1(container=container)

    return

def cf_local_store_peer_list_as_customlist_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('cf_local_store_peer_list_as_customlist_1() called')
    
    action_results_data_0 = phantom.collect2(container=container, datapath=['run_query_1:action_result.data.*.peer', 'run_query_1:action_result.data.*.count', 'run_query_1:action_result.data.*.priority', 'run_query_1:action_result.parameter.context.artifact_id'], action_results=results )
    container_property_0 = [
        [
            container.get("id"),
        ],
    ]

    parameters = []

    action_results_data_0_0 = [item[0] for item in action_results_data_0]
    action_results_data_0_1 = [item[1] for item in action_results_data_0]
    action_results_data_0_2 = [item[2] for item in action_results_data_0]
    container_property_0_0 = [item[0] for item in container_property_0]

    parameters.append({
        'peer': action_results_data_0_0,
        'count': action_results_data_0_1,
        'priority': action_results_data_0_2,
        'container': container_property_0_0,
    })
    ################################################################################
    ## Custom Code Start
    ################################################################################

    # Write your custom code here...

    ################################################################################
    ## Custom Code End
    ################################################################################    

    # call custom function "local/store_peer_list_as_customlist", returns the custom_function_run_id
    phantom.custom_function(custom_function='local/store_peer_list_as_customlist', parameters=parameters, name='cf_local_store_peer_list_as_customlist_1', callback=format_3)

    return

def playbook_local_local_Malware_Critical_Peer_Container_ch02_1(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs):
    phantom.debug('playbook_local_local_Malware_Critical_Peer_Container_ch02_1() called')
    
    # call playbook "local/Malware Critical Peer Container ch02", returns the playbook_run_id
    playbook_run_id = phantom.playbook(playbook="local/Malware Critical Peer Container ch02", container=container)

    return

def on_finish(container, summary):
    phantom.debug('on_finish() called')
    # This function is called after all actions are completed.
    # summary of all the action and/or all details of actions
    # can be collected here.

    # summary_json = phantom.get_summary()
    # if 'result' in summary_json:
        # for action_result in summary_json['result']:
            # if 'action_run_id' in action_result:
                # action_results = phantom.get_action_results(action_run_id=action_result['action_run_id'], result_data=False, flatten=False)
                # phantom.debug(action_results)

    return