import requests
import json
import os
import time
from dotenv import load_dotenv

# Load information for owencloud and telegram
load_dotenv()

# Get Token for OwenCloud
def get_token():
    login = os.getenv("LOGIN")
    password = os.getenv("PASSWORD")
    if not login or not password:
        raise ValueError("Логин или пароль не заданы в .env")

    data = {'login': login, 'password': password}
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    req = requests.post("https://api.owencloud.ru/v1/auth/open/", json=data, headers=headers)
    if req.status_code == 200:
        answer = req.json()
        token = "Bearer " + answer["token"]
        return token
    else:
        print(f"Ошибка авторизации: {req.status_code}, {req.text}")
        return None


# Load previous values from a file
def load_previous_values(file_path="previous_values.json"):
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            return json.load(file)
    return {}


# Save current values to a file
def save_current_values(data, file_path="previous_values.json"):
    with open(file_path, "w") as file:
        json.dump(data, file, indent=4)


# Device parsing and comparison
def monitor_changes():
    previous_values = load_previous_values()
    token = get_token()
    if not token:
        print("Не удалось получить токен. Завершаем работу.")
        return

    device_id = "459205"
    headers = {'Authorization': token}
    data = json.dumps({'filter': ''})

    while True:
        try:
            req = requests.post(f"https://api.owencloud.ru/v1/device/{device_id}", data=data, headers=headers)
            if req.status_code != 200:
                print(f"Ошибка запроса устройства: {req.status_code}, {req.text}")
                time.sleep(60)  # Подождать минуту и попробовать снова
                continue

            nwer = req.json()
            current_values = {}

            # Check and process the parameters list
            if 'parameters' in nwer and isinstance(nwer['parameters'], list):
                for item in nwer['parameters']:
                    if isinstance(item, dict) and 'code' in item and item['code']:
                        code = item['code']
                        value = item['value']
                        current_values[code] = value

                        # Compare with previous values
                        if code in previous_values:
                            if previous_values[code] != value:
                                print(f"Изменение: {item['name']} (Code: {code}): {previous_values[code]} -> {value}")
                        else:
                            print(f"Новый параметр: {item['name']} (Code: {code}), Value: {value}")

            # Save current values for future comparison
            save_current_values(current_values)
            previous_values = current_values

        except Exception as e:
            print(f"Ошибка в процессе мониторинга: {e}")

        # Pause for 1 minute
        time.sleep(10)


if __name__ == "__main__":
    monitor_changes()
