# Copyright (c) 2026 Meteo Ponte San Nicoḷ. Tutti i diritti riservati.
#
# Questo plugin consente di calcolare il parametro "inHeatindex", ossia l'indice di calore basato sulla temperatura e umidità interni.
#
# Requisiti:
#    1. Weewx 4.2 o successivi
#    2. Temperatura e umidità interni rilevati
#
# Istruzioni per l'installazione:
#    1. Fermare il processo "weewxd" (a seconda del metodo di installazione)
#    2. Inserire questo file nella cartella bin/user
#    3. Nel file configurazione weewx.conf, sottosezione [Engine][[Services]], aggiungere "inHeatindexService" alla riga "xtype_services". Ad esempio:
#
#        [Engine]
#            [[Services]]
#                xtype_services = weewx.wxxtypes.StdWXXTypes, weewx.wxxtypes.StdPressureCooker, weewx.wxxtypes.StdRainRater, weewx.wxxtypes.StdDelta, user.inheatindex.inHeatindexService
#
#    4. Aggiungere nella sottosezione [StdWXCalculate][[Calculations]] la riga:
#
#        inHeatindex = software
#
#    5. Opzionalmente, aggiungere la seguente sezione:
#
#        [inHeatindex]
#            algorithm = new   # Oppure "old"
#
#    6. Riavviare il processo "weewxd"

import weewx
import weewx.units
weewx.units.obs_group_dict['inHeatindex'] = "group_temperature"

import weewx.xtypes
import weewx.wxxtypes
from weewx.engine import StdService
from weewx.units import ValueTuple, CtoF

class inHeatindex(weewx.xtypes.XType):

    def __init__(self, algorithm='new'):
        self.algorithm = algorithm.lower()
        
    def get_scalar(self, obs_type, record, db_manager):
        if obs_type != 'inHeatindex':
            raise weewx.UnknownType(obs_type)
            
        if 'inTemp' not in record or record['inTemp'] is None and 'inHumidity' not in record or record['inHumidity'] is None:
            raise weewx.CannotCalculate(obs_type)
            
        if record['usUnits'] == weewx.US:
            val = weewx.wxformulas.heatindexF(record['inTemp'], record['inHumidity'],
                                              algorithm=self.algorithm)
            u = 'degree_F'
        else:
            val = weewx.wxformulas.heatindexC(record['inTemp'], record['inHumidity'],
                                              algorithm=self.algorithm)
            u = 'degree_C'
        return ValueTuple(val, u, 'group_temperature')
        
        
class inHeatindexService(weewx.engine.StdService):

    def __init__(self, engine, config_dict):
        super(inHeatindexService, self).__init__(engine, config_dict)
        
        try:
            algorithm = config_dict['inHeatindex']['algorithm']
        except KeyError:
            algorithm = 'new'
                
        self.inhi = inHeatindex(algorithm)
        
        weewx.xtypes.xtypes.append(self.inhi)
        
    def shutDown(self):
        weewx.xtypes.xtypes.remove(self.inhi)