import requests
import json
import os
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
#Device parsing
def main():

    codes_to_search = [
        "P16385", "P16386", "P16387", "P16388", "P16389", "P16390", "P16391",
        "P16392", "P16393", "P16394", "P16395", "P16396", "P16397", "P16398"
    ]
    token = get_token()
    if not token:
        print("Не удалось получить токен. Завершаем работу.")
        return

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

    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}")
        return

    #nswer = req.json()
    #print(req.text)
    #print("Response structure:", json.dumps(nswer, indent=2))
    nwer = req.json()  # Store the response in 'nwer'

    # 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'] in codes_to_search:
                print(f"Code: {item['code']}, Value: {item['value']}")
    else:
        print("Unexpected response format or 'parameters' key is missing.")


if __name__ == "__main__":
    main()
