import requests
from datetime import datetime, timezone, timedelta
import json

"""
SBACK-856: AIS is only truncating or removing deleted associations 
from asset documents when a new address is associated

Script to associate an IP back and forth between two MACs.

NOTE: Short on time skipping error handling...
"""

# utcnow() has funky issues (bug?) with using timedelta() to add/subtract
# timestamps. So, ditched it for now(timezone.utc).
# Sidenote, utcnow() also isn't timezone aware.
current_time = datetime.now(timezone.utc)
current_time_str = current_time.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
print (f'starting time now is = {current_time_str}')

# Subtract 4wks from current UTC time. This will be the starting time that is increased in
# a loop by 2min for each request made.
current_time_sub = current_time - timedelta(weeks=4)

# There may be a magical python lib that creates the exact valid time format for the API.
# I didn't see it when poking around for UTC timestamps. So, the valid format is 
# manufactured by hand here instead.
current_time_sub_str = current_time_sub.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
print(f'current_time_sub_str = {current_time_sub_str}')

url = "https://sitestore-test-reg4.hq.dragos.services/assets/api/v4/associateAddresses"
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Basic YWRtaW46RHJAZ29zU3lzdDNt'
}

# json grabbed from POSTMAN. Could have just used python code generated by POSTMAN
# but variable substitution into a python dict (produced by json.loads()) is easier/cleaner
# than doing it a python string.
# Using 'r' for 'raw' data to keep python from complaining about json value,'true',
# not being defined.
payload_json = r'''{
    "lookups": {
        "mac": {
            "type": "coordinates",
            "coordinates": {
                "type": "MAC",
                "networkId": "test_network1",
                "value": "address_stub"
            },
            "createIfMissing": true
        },
        "ip": {
            "type": "coordinates",
            "coordinates": {
                "type": "IP",
                "value": "1.2.3.4",
                "networkId": "test_network1"
            },
            "createIfMissing": true
        }
    },
    "associateLookups": {
        "mac": ["ip"]
    },
    "at": "time_stub"
    }''' 

MAC1 = "DE:AD:DE:AD:BE:EF"
MAC2 = "BE:EF:BE:EF:DE:AD"

for i in range(3):

    print(f'====> loop({i})')
    print(f'current_time_sub_str = {current_time_sub_str}')

    # Convert json into python object (dict) for easier variable substitution of incrementing
    # timestamp and MAC[1|2]
    payload = json.loads(payload_json)
    payload['lookups']['mac']['coordinates']['value'] = MAC1
    payload['at'] = current_time_sub_str

    # Make request and output the status code and response
    response = requests.request("POST", url, headers=headers, json=payload, verify=False)
    print(f'==> status code = {response.status_code}')
    print(response.text)

    # Add 2min to current_time_sub before next request
    add_2m = current_time_sub + timedelta(minutes=2)
    current_time_sub_str = add_2m.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    print(f'current_time_sub_str = {current_time_sub_str}')

    # Setup and make 2nd request
    payload = json.loads(payload_json)
    payload['lookups']['mac']['coordinates']['value'] = MAC2
    payload['at'] = current_time_sub_str
    response = requests.request("POST", url, headers=headers, json=payload, verify=False)
    print(f'==> status code = {response.status_code}')
    print(response.text)

    # Add 2min to current_time_sub before next request
    add_2m = add_2m + timedelta(minutes=2)
    current_time_sub_str = add_2m.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    current_time_sub = add_2m
