import requests
import json

from powerx_energy_api import config
from powerx_energy_api import exceptions

class UserAPI():

    def __init__(self):
        self.access_token=None

    def login(self,username,password):
        print(f"api {config.BASE_USER_API_URL}/customer/login")
        try:
            x = requests.post(f'{config.BASE_USER_API_URL}/customer/login',
    json={"username":username,'password':password})
            print(f"status code {x.status_code} text {x.text}")
            if x.status_code!=200:
                raise exceptions.InvalidCredentialsError
            tx= json.loads(x.text)
            self.access_token = tx['access_token']
            return x
            print(f"response {self.access_token}")
        except requests.exceptions.ConnectionError:
            raise exceptions.ConnectionError


    def get_current_heat(self,username,password):
        x = self.login(username,password)
        customer_info = self.get_customer_info()
        print(f"got customer info")
        if customer_info['preferences']['selected_hub_id'] is None:
            return 'No hub found',401
        hub_id = customer_info['preferences']['selected_hub_id']
        try:    
            x = requests.get(f'{config.BASE_USER_API_URL}/device/{hub_id}/heat/all/current_statistics',
        headers={
            'authorization':'Bearer '+self.access_token
        })
            print(f"heat output {x.text}")
            data = json.loads(x.text)
            unit = customer_info['preferences']['temperature_unit']
            data['summary']['avg']=data['summary']['avg_celsius']
            if unit=='fahrenheit':
                data['summary']['avg']=data['summary']['avg_fahrenheit']
            data['summary']['unit']=unit    
            return data,200
        except requests.exceptions.ConnectionError:
            raise exceptions.ConnectionError        

    def get_current_water(self,username,password):
        self.login(username,password)
        customer_info = self.get_customer_info()
        print(f"got customer info")
        if customer_info['preferences']['selected_hub_id'] is None:
            return 'No hub found',401
        hub_id = customer_info['preferences']['selected_hub_id']
        try:  
            x = requests.get(f'{config.BASE_USER_API_URL}/device/{hub_id}/water/all/current_statistics',
        headers={
            'authorization':'Bearer '+self.access_token
        })
            data = json.loads(x.text)
            unit = customer_info['preferences']['tank_capacity_unit']
            data['summary']['avg']=data['summary']['total_water_liters']
            if unit=='gallons':
                data['summary']['avg']=data['summary']['total_water_gallons']

            data['summary']['unit']=unit
            return data,200
        except requests.exceptions.ConnectionError:
            raise exceptions.ConnectionError        

    def get_customer_info(self):
        try:
            x = requests.get(f'{config.BASE_USER_API_URL}/customer',
        headers={
            'authorization':'Bearer '+self.access_token
        })
            return json.loads(x.text)
        except requests.exceptions.ConnectionError:
            raise exceptions.ConnectionError         
   
if __name__ == "__main__":
    api = UserAPI()
    api.login('manuel@powerx.co','test12d3')