# Author: Charles Jiron
# iOS Wallpaper Change via Python Script - API V2

# Python Libraries
import base64
import csv
import os
from datetime import datetime

import requests

### SCRIPT VARIABLES ###
API_V2_Token = "YOUR_API_V2_TOKEN"  # API V2 TOKEN
imagePath = "YOUR_IMAGE_PATH"  # Image Path
where = 3  # 1: Lock screen | 2: Home (icon list) screen | 3: Lock and Home screens.
PolicyID = "YOUR_POLICY_ID"  # Policy ID
### END OF VARIABLES ###

### FILE CHECK & CREATION ###
DeviceWallpaperFile = "Addigy-iOS-Wallpaper-Device-List-Python.csv"

print("FILE CHECK & CREATION")
print("====================")

if os.path.isfile(DeviceWallpaperFile):
    print("File exists...REMOVING Duplicate.")
    os.remove(DeviceWallpaperFile)
else:
    print("File does not exist...CREATING File")
    # Create an empty file
    open(DeviceWallpaperFile, "w").close()
### END OF FILE CHECK & CREATION ###

### START ENCODING OF IMAGE ###
# Get the base 64 of Wallpaper Image - Read and encode image as BASE64
with open(imagePath, "rb") as image_file:
    base_64_image = base64.b64encode(image_file.read()).decode("utf-8")
### END OF ENCODING IMAGE ###

### START OF DEVICE LIST API ENDPOINT ###
# Get policy devices API URL
deviceList_url = "https://api.addigy.com/api/v2/devices"

deviceList_headers = {
    "accept": "application/json",
    "x-api-key": API_V2_Token,  # make sure AddigyToken is defined
    "Content-Type": "application/json"
}

deviceList_payload = {
    "desired_fact_identifiers": [
        "agentid",
        "device_name",
        "serial_number",
        "policy_id",
        "hardware_model",
        "device_model_name"
    ],
    "page": 1,
    "per_page": 300,
    "query": {
        "filters": [
            {
                "audit_field": "os_version",
                "operation": ">",
                "range_value": "",
                "type": "string",
                "value": "0"
            }
        ],
        "policy_id": PolicyID,  # make sure PolicyID is defined
        "search_any": ""
    },
    "sort_direction": "asc",
    "sort_field": "serial_number"
}

deviceList_response = requests.post(deviceList_url, headers=deviceList_headers, json=deviceList_payload)

# Store the response
try:
    DeviceList = deviceList_response.json()
except ValueError:
    print("Response is not valid JSON")
    print(deviceList_response.text)
    exit(1)


### END OF DEVICE LIST API ENDPOINT ###


def process_device_list(json_data, output_file, AddigyToken, encodedImage, location):
    items = json_data.get("items", [])

    # Print headers
    print("========================================")
    print(f"Device Wallpaper List - {datetime.now().strftime('%Y-%m-%d %H:%M')}")
    print("========================================")

    # Prepare CSV
    with open(output_file, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([
            "Device Name", "Serial Number", "Agent ID",
            "Device Model", "Policy ID", "Wallpaper Change Status"
        ])

        for item in items:
            # Extract the desired fields for each item
            facts = item.get("facts", {})
            device_name = facts.get("device_name", {}).get("value", "N/A")
            serial_number = facts.get("serial_number", {}).get("value", "N/A")
            agent_id = facts.get("agentid", {}).get("value", "N/A")
            policy_id = facts.get("policy_id", {}).get("value", "N/A")
            device_model = facts.get("device_model_name", {}).get("value", "N/A")

            # Extract the desired model type
            if device_model in ["iPhone", "iPad"]:
                print(f"Device Name: {device_name}")
                print(f"Serial Number: {serial_number}")
                print(f"Device Model: {device_model}")
                print(f"Agent ID: {agent_id}")

                ### START OF WALLPAPER API ENDPOINT ###
                # Call API V2 - Wallpaper endpoint
                wallpaper_url = "https://api.addigy.com/api/v2/mdm/settings/wallpaper"

                wallpaper_payload = {
                    "agent_id": agent_id,
                    "image": encodedImage,
                    "where": location
                }
                wallpaper_headers = {
                    "accept": "application/json",
                    "x-api-key": AddigyToken,
                    "Content-Type": "application/json"
                }

                try:
                    response = requests.post(wallpaper_url, headers=wallpaper_headers, json=wallpaper_payload)

                    response.raise_for_status()
                    status = "Successful"
                    print("Wallpaper Change - Successful!")
                except (requests.HTTPError, requests.RequestException) as e:
                    message = f"Wallpaper Change - Request Failed - {e}"
                    status = "Failure"
                    print(message)
                print(f"Logging to {output_file}......")
                print("========================================")
                ### END OF WALLPAPER API ENDPOINT ###

                # Writing to the CSV FILE
                writer.writerow([
                    device_name, serial_number, agent_id,
                    device_model, policy_id, status
                ])


# Calling the Function
process_device_list(DeviceList, DeviceWallpaperFile, API_V2_Token, base_64_image, where)
