# coding: utf-8

# flake8: noqa

"""
    Enyday API

    This API allows integration with the Enyday platform, providing access to user authentication, user details, authorization data, address information, and power consumption data. It helps in integrating Enyday into platforms like Home Assistant. 

    The version of the OpenAPI document: 1.0.0
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


__version__ = "1.0.0"

# import apis into sdk package
from EnydayPy.api.default_api import DefaultApi

# import ApiClient
from EnydayPy.api_response import ApiResponse
from EnydayPy.api_client import ApiClient
from EnydayPy.configuration import Configuration
from EnydayPy.exceptions import OpenApiException
from EnydayPy.exceptions import ApiTypeError
from EnydayPy.exceptions import ApiValueError
from EnydayPy.exceptions import ApiKeyError
from EnydayPy.exceptions import ApiAttributeError
from EnydayPy.exceptions import ApiException

# import models into sdk package
from EnydayPy.models.address_response import AddressResponse
from EnydayPy.models.address_response_addresses import AddressResponseAddresses
from EnydayPy.models.address_response_submeters import AddressResponseSubmeters
from EnydayPy.models.auth_token_response import AuthTokenResponse
from EnydayPy.models.eloverblik_authorization_response import EloverblikAuthorizationResponse
from EnydayPy.models.power_consumption_response import PowerConsumptionResponse
from EnydayPy.models.power_consumption_response_invoiced import PowerConsumptionResponseInvoiced
from EnydayPy.models.user_details_response import UserDetailsResponse
from EnydayPy.models.user_details_response_periods import UserDetailsResponsePeriods
from EnydayPy.models.user_details_response_roles import UserDetailsResponseRoles
from EnydayPy.models.user_details_response_user_btms import UserDetailsResponseUserBtms
from EnydayPy.models.user_user_body import UserUserBody

from urllib3.exceptions import InsecureRequestWarning
import urllib3
import pandas as pd
from datetime import datetime, timedelta

# Suppress only the single InsecureRequestWarning from urllib3
urllib3.disable_warnings(InsecureRequestWarning)


class EnydayClient:
    def __init__(self):
        # Initialize configuration and client without auth
        self.configuration = Configuration()
        self.configuration.verify_ssl = False  # Disable SSL verification
        self.api_client = ApiClient(self.configuration)
        self.api_instance = DefaultApi(self.api_client)


    def connect(self, username: str, password: str):
        """
        Authenticates the user and configures the API client with an authorization token.
        
        :param username: The username for Enyday (email).
        :param password: The password for Enyday.
        :return: None
        """
        try:
            # Attempt to retrieve the auth token
            auth_data = {"email": username, "password": password}
            response: AuthTokenResponse = self.api_instance.get_user_auth_token(auth_data)
            
            # Set the token in the configuration as API key
            self.api_client.default_headers['Authorization'] = response.auth_token
            
            print("Successfully connected and authenticated!")
        except Exception as e:
            print(f"Authentication failed: {e}")

    def get_user_details(self):
        """
        Retrieves user details, using the authenticated API client.
        
        :return: User details object
        """
        try:
            # Now any call here will include the Authorization header
            return self.api_instance.get_user_details()
        except Exception as e:
            print(f"Failed to retrieve user details: {e}")

    def get_eloverblik_authorization(self, user_id: int):
        """
        Retrieves Eloverblik authorization details, using the authenticated API client.
        
        :return: Eloverblik authorization object
        """
        try:
            return self.api_instance.get_eloverblik_authorizations(user_id = user_id)
        except Exception as e:
            print(f"Failed to retrieve Eloverblik authorization: {e}")

    def get_address_by_user_id(self, user_id: int):
        """
        Retrieves address details, using the authenticated API client.
        
        :return: Address details object
        """
        try:
            return self.api_instance.get_addresses_by_user_id(user_id = user_id)
        except Exception as e:
            print(f"Failed to retrieve address details: {e}")

    def get_power_consumption_by_user_and_address_ids(self, user_id: int, address_id: int,
                                                      begin: datetime = datetime.now() - timedelta(days=1), end: datetime = datetime.now(),
                                                       as_dataframe: bool = False):
        """
        Retrieves power consumption details, using the authenticated API client.

        :param as_dataframe: Return the data as a pandas DataFrame.
        :return: Power consumption object
        """
        try:
            response = self.api_instance.get_hourly_power_data(user_id = user_id, address_id = address_id, begin = begin, end = end)
            if as_dataframe:
                return self.convert_power_consumption_to_dataframe(response)
            else:
                return response
        except Exception as e:
            print(f"Failed to retrieve power consumption details: {e}")
    
    def convert_power_consumption_to_dataframe(self, power_consumption: PowerConsumptionResponse):
        """
        Converts the power consumption response to a pandas DataFrame.
        
        :param power_consumption: The power consumption response object.
        :return: The power consumption data as a pandas DataFrame.
        """
        try:
            # Convert the power consumption data to a DataFrame
            data = power_consumption.invoiced
            data = [x.dict() for x in data]
            df = pd.DataFrame(data)
            return df
        except Exception as e:
            print(f"Failed to convert power consumption to DataFrame: {e}")