# PatternV2.py
# Manage advanced PatternV2 actions (Solace Pro toys)

import requests
import time
from LvsConstant import LvsConstant

def SendPatternV2Setup(actions):
    """
    Set up a PatternV2 sequence.

    Example actions parameter:
    actions: [
        { "ts": 0, "pos": 0 },
        { "ts": 1000, "pos": 100 },
        { "ts": 2000, "pos": 0 },
        { "ts": 3000, "pos": 100 },
        { "ts": 4000, "pos": 0 },
        { "ts": 5000, "pos": 100 },
        { "ts": 6000, "pos": 0 },
        { "ts": 7000, "pos": 100 },
        { "ts": 8000, "pos": 0 },
        { "ts": 9000, "pos": 100 },
        { "ts": 10000, "pos": 0 }
    ]
    - ts: timestamp in milliseconds (relative to start time)
    - pos: strength level (0-100)
    """
    url = f"{LvsConstant.domainUrl}/command"
    data = {
        "command": "PatternV2",
        "type": "Setup",
        "actions": actions,
        "apiVer": 1
    }

    response = requests.post(url, json=data)
    if response.status_code == 200:
        print(f"✅ SendPatternV2Setup Response: {response.json()}")
    else:
        print(f"❌ SendPatternV2Setup Failed. Status Code: {response.status_code}")

def SendPatternV2Play(toy_id, start_time, offset_time):
    """
    Start playing a configured PatternV2 sequence.
    """
    url = f"{LvsConstant.domainUrl}/command"
    data = {
        "command": "PatternV2",
        "type": "Play",
        "toy": toy_id,
        "startTime": start_time,
        "offsetTime": offset_time,
        "apiVer": 1
    }

    response = requests.post(url, json=data)
    if response.status_code == 200:
        print(f"✅ SendPatternV2Play Response: {response.json()}")
    else:
        print(f"❌ SendPatternV2Play Failed. Status Code: {response.status_code}")

def GetPatternV2SyncTime():
    """
    Sync the local time with the toy server to calculate the estimated offset time.
    
    offsetTime = (T2 - T1), in milliseconds.
    
    Returns:
        offset_time_ms (int): Estimated offset time in milliseconds.
    """
    url = f"{LvsConstant.domainUrl}/command"
    data = {
        "command": "PatternV2",
        "type": "SyncTime",
        "apiVer": 1
    }

    try:
        t1 = int(time.time() * 1000)  # T1: time before sending, in ms
        response = requests.post(url, json=data)
        t2 = int(time.time() * 1000)  # T2: time after receiving, in ms

        if response.status_code == 200:
            offset_time = round((t2 - t1)/1000, 2)
            print(f"✅ Sync success. Estimated offsetTime = {offset_time} ms")
            return offset_time
        else:
            print(f"❌ Sync failed. Response code: {response.status_code}")
            return 1
    except Exception as e:
        print(f"❌ SyncTime error: {e}")
        return f"❌ SyncTime error: {e}"

def StopPatternV2(toy_id):
    """
    Stop a running PatternV2 sequence. Same as `LovenseRemoteSDK.StopFunction()`.
    """
    url = f"{LvsConstant.domainUrl}/command"
    data = {
        "command": "PatternV2",
        "type": "Stop",
        "toy": toy_id,
        "apiVer": 1
    }

    response = requests.post(url, json=data)
    if response.status_code == 200:
        print(f"✅ StopPatternV2 Response: {response.json()}")
    else:
        print(f"❌ StopPatternV2 Failed. Status Code: {response.status_code}")