"""
Created on Mon Oct 6

@author: qingkaikong
"""

import json
import requests
from datetime import datetime

import aqi

# %% Define class
class PurpleAirReader(object):
  
  def __init__(self, identity):
    """
    
    Args:
      identity: path of the identify json file. 

    Returns:
      None.

    """
    self.identity = json.load(open(identity, 'r'))
  
  def _form_url(self):
    return (f'https://www.purpleair.com/json?key={self.identity["key"]}'
            f'&show={self.identity["id"]}')
  
  def request_sensor_data(self):
    """Request data from Purple Air. 

    Returns:
      data (dictionary): Parsed data in from the purple air sensor.

    """
    url = self._form_url()
    resp = requests.get(url=url)
    data = resp.json()
    return data
  
  def print_raw_sensor_recordings(self):
    """Print out the raw data from purple air. 

    Returns:
      None.

    """
    
    sensor_data = self.request_sensor_data()
    print(json.dumps(sensor_data, indent=4, sort_keys=True))
    
  def _get_pm2pt5_from_sensor(self, sensor):
    """Function get the PM2.5 stats and the update time. 

    Args:
      sensor: sensor data requested from purple air.

    Returns:
      pm2pt5_stats: dictionary stores the PM2.5 AQI stats for the
        current value, 10 minutes average, 30 minutes average, 1 hour
        average, 6 hours average, 24 hours average and 1 week average.
      last_update: time string for the last update.

    """
    
    pm2pt5_info = json.loads(sensor['Stats'])
    pm2pt5_stats = {
      "current": pm2pt5_info['v'],
      "10_min_avg": pm2pt5_info['v1'],
      "30_min_avg": pm2pt5_info['v2'],
      "1_hour_avg": pm2pt5_info['v3'],
      "6_hour_avg": pm2pt5_info['v4'],
      "24_hour_avg": pm2pt5_info['v5'],
      "1_week_avg": pm2pt5_info['v6'],
      }
    
    # We get the last update time to UTC string. 
    last_update = datetime.utcfromtimestamp(
      pm2pt5_info['lastModified']/1000).strftime('%Y-%m-%d %H:%M:%S')
    
    # We convert the raw readings to AQI.
    pm2pt5_stats= {
      k: int(self.pm2pt5_to_aqi(v)) for k, v in pm2pt5_stats.items()}
    
    return pm2pt5_stats, last_update
  
  def pm2pt5_to_aqi(self, pm25_value):
    return aqi.to_aqi([(aqi.POLLUTANT_PM25, pm25_value)])
    
  def get_sensor_summary(self):
    """Function to get a quick summary from purple air. 
    
    Returns:
      None.

    """
    sensor_data = self.request_sensor_data()
    # We get the current recording. 
    sensor1 = sensor_data['results'][0]
    sensor2 = sensor_data['results'][1]
    sensor1_label = sensor1['Label']
    
    # We get the last update time to UTC string. 
    last_update = datetime.utcfromtimestamp(
      sensor1['LastUpdateCheck']).strftime('%Y-%m-%d %H:%M:%S')
    
    # We get the pm2.5 stats and update time. 
    pm2_5_sensor1, last_update_1 = self._get_pm2pt5_from_sensor(sensor1)
    pm2_5_sensor2, last_update_2 = self._get_pm2pt5_from_sensor(sensor2)
    
    # We convert the dictionary to json for pretty print. 
    pm2_5_aqi_sensor1_json = json.dumps(pm2_5_sensor1, indent=4)
    pm2_5_aqi_sensor2_json = json.dumps(pm2_5_sensor2, indent=4)
    
    # We get the temperature and humidity readings. 
    temp_f = float(sensor1['temp_f'])
    temp_c = (temp_f - 32) * 5.0/9.0
    humidity = sensor1['humidity']
    
    # Print out the summary. 
    print(f'################# Report from the sensor at {sensor1_label}:\n'
          f'Last update: {last_update} UTC\n'
          f'Current temp: {temp_c:.1f}C ({temp_f:.1f}F)\n'
          f'Current humidity: {humidity}\n\n'
          f'Sensor 1 PM2.5 AQI, updated at {last_update_1} UTC: \n'
          f'{pm2_5_aqi_sensor1_json}\n'
          f'Sensor 2 PM2.5 AQI, updated at {last_update_2} UTC: \n'
          f'{pm2_5_aqi_sensor2_json}\n'
          )

  
# %% Run example
if __name__ == "__main__":
  purple_air_reader = PurpleAirReader('./identity.json')
  purple_air_reader.get_sensor_summary()
  