import requests
import json
import uuid
from requests_toolbelt import MultipartEncoder
from requests.auth import HTTPBasicAuth

api_endpoint = 'http://localhost:8080/Olog/logs/multipart'

# Prepare log entry payload
log_entry = {
    "owner": "dev",
    "description": "New entry using Olog/logs/multipart with one attachment.\n",
    "level": "INFO",
    "title": "test4.py",
    "logbooks": [{"name": "controls"}],
    "attachments":[
        # {"id": str(uuid.uuid4()), "name": "FREIAlogo-v3_March19.png"}
        {"id": str(uuid.uuid4()), "filename": "FREIAlogo-v3_March19.png"}
    ]
}

# Prepare the log entry payload as JSON
json_data = json.dumps(log_entry)
json_filename = json.dumps({"filename": "FREIAlogo-v3_March19.png"})
json_descr = json.dumps({"fileMetadataDescription": "image/png"})

# Prepare the multipart encoder
multipart_data = MultipartEncoder(
    fields={
        'logEntry': ('logEntry.json', json_data, 'application/json'),
        'files': ('filename', json_filename, 'application/json'),
        'files': ('fileMetadataDescription', json_descr, 'application/json'),
        'files': ('FREIAlogo-v3_March19.png', open('FREIAlogo-v3_March19.png', 'rb'), 'application/octet-stream')

        # 'files': ('FREIAlogo-v3_March19.png', open('FREIAlogo-v3_March19.png', 'rb'), 'application/json')
    }
)

# Set the Content-Type header with the boundary
headers = {
    'Content-Type': multipart_data.content_type
}

try:
    response = requests.put(api_endpoint, headers=headers, data=multipart_data, auth=HTTPBasicAuth('admin', '1234'))
    if response.status_code == 200:
        print("Log entry created successfully.")
        print(f"Response text: {response.text}")
    else:
        print(f"Failed to create log entry. Status code: {response.status_code}")
        print(f"Response text: {response.text}")
except Exception as e:
    print("An error occurred: ",{str(e)})